pushing items to array in typescript in a structured way - typescript2.0

I have these items here that I want to push to an array in a set format.
I have declared my array this way
finalCount = [];
Now I want this array to have items in this format:
animal: Count
For e.g:
dog: 3
cat: 4
cow: 1
And each item in the array should be accessible by providing a index number as well. for e.g finalCount[0] should pick dog.
I tried to push items this way
this.finalCount.push(this.animal, this.count);
but each item here doesn't go together.
How do I get that.

To push items in your final count array, you can leverage synthax originally introduced with ES2015, computed properties
Now if you want to define the TypeScript type for objects in the finalCount array. You should create the following interface:
interface FinalCountItem {
[animal: string]: number;
}
finalCount: FinalCountItem[] = [];
this.finalCount.push({[this.animal]: this.count});

Related

How to feed a nested collection in Kotlin?

Here is the code:
var list = mutableListOf<Set<String>>()
list[0] = mutableSetOf("bar")
list[0].add("foo") // doesn't compile
Why it doesn't compile ?
And how can I add an element to a nested collection ?
This is because you have set the element type of the mutable list as Set, which is immutable.
You should specify that it has a mutable set, for example: mutableListOf<MutableSet<String>>

Kotlin: ArrayList<Object> storing variables as values instead of reference [duplicate]

This question already has answers here:
Java ArrayList copy
(10 answers)
Closed 2 years ago.
I'm having an issue where I assign a variable based on data that is being received from a server (in JSON).
I have two class variables
teams - which will be changed based on user interaction
reset_teams - which should always stay the same as the original list so that a user can reset all values whenever they choose.
These variables are used to (re-)populate a RecyclerView at various times based on user interaction (i.e., pressing a button inside of the app)
My problem is that any time I make a change to an object in the teams ArrayList, it also makes a change to the reset_teams ArrayList, as if they are somehow connected (similar to pass by value/reference in a function).
I am somewhat new to Kotlin, so it's quite possible I am missing something, but I'm wondering how I can keep the reset_teams ArrayList exactly the same at all times, even if the teams ArrayList has changes to different properties of the objects it stores?
// Class variables
var teams: ArrayList<myObject> = ArrayList()
var reset_teams: ArrayList<myObject> = ArrayList()
// Function to handle JSON after receiving data from remote server
private fun handleJson(jsonString: String?) {
val jsonArray = JSONArray(jsonString)
val list = ArrayList<myObject>()
var x = 0
while (x < jsonArray.length()) {
val jsonObject = jsonArray.getJSONObject(x)
list.add(
myObject(// a bunch of code to make an object of type myObject)
)
x++
}
teams = list
reset_teams = list
test() // Change a property
}
private fun test(){
teams[0].someProperty = 10
println(teams) // The someProperty of the first element of the ArrayList has been correctly assigned to 10
println(reset_teams) // The someProperty of the first element of the ArrayList has been changed to 10 even though the reset_teams was never assigned a new value
}
By assigning
teams = list
reset_teams = list
both list teams and list reset_teams reference the same list (space) in memory (heap). With teams[0].someProperty = 10 you change someProperty of the first element of this referenced list to 10. Since reset_teams references the same list, it also shows the changes.
In order to fix this unintended behaviour you will have to add copies of the objects to both lists teams and reset_teams. If class myObject is a data class, then you can add a copy by calling teams.add(m.copy()) where m is an instance of class myObject.
Remarks:
use camelCase for variable names: resetTeams instead of reset_teams
start class names with a capital letter: MyObject instead of myObject
prefer immutable objects if possible

Match argument object that has a property equal to (using Mockk)

I have looked around for a similar question, but cannot find a solution.
I have a couple of instances to the same type of object. As a simple example, a Pen object. This class contains size (Int) and color (String) properties. I need to mock a function (such as calculatePrice) that takes in this type of object. I would like it to return a result based on one of the properties.
every { calculatePrice(pen : Pen) } returns 3
every { calculatePrice(pen2 : Pen) } returns 4
Because this call is nested within another function, I cannot guarantee that the address of the object is the same, so I am attempting to get around this by checking a property value, such as pen.size. If there is a way to make sure the value of the object is the same, not the reference, that would solve my problem too.
Using Mockito, I would use argThat(pen -> pen.size() == 2)
Any recommendations would be much appreciated.
match should work, see https://mockk.io/#matchers
For example:
every { calculatePrice( match { it.size == 2 } ) } returns 3

copy one arraylist to another arraylist in kotlin

I am trying to copy one ArrayList to another ArrayList in Kotlin
1st ArrayList:
private var leadList1: ArrayList<Lead> = ArrayList()
2nd ArrayList:
val leadList2: ArrayList<Lead?>?
I tried to use addAll(). leadList1.addAll(leadList2)
But its not working.
Error showing:
Required: Collection<Lead>
Found: kotlin.collections.ArrayList<Lead?>?
This isn't safe to do, because your first list can only contain objects of type Lead, while your second one has Lead? as its type parameter, meaning that it might contain null values. You can't add those to the first list.
The solution for this problem will depend on your context, but you can either let the first list contain nullable elements too:
private var leadList1: ArrayList<Lead?> = ArrayList()
Or you can add only the non-null elements of the second list to the first one:
leadList1.addAll(leadList2.filterNotNull())
And in either case, you'll have to perform a null check on leadList2, because the entire list itself is marked as potentially null as well, signified by the last ? of the type ArrayList<Lead?>?.
if (leadList2 != null) {
leadList1.addAll(leadList2.filterNotNull())
}
You can simply pass another List instance into the constructor of your new List
val originalList = arrayListOf(1,2,3,4,5)
val orginalListCopy = ArrayList(originalList)
Do this:
leadList1.addAll(leadList2.orEmpty().filterNotNull())
And to filter by property you can do like this:
leadList1.addAll(leadList2.orEmpty().filter { item -> item?.type == YourTypeString })

flex 3 iterate through object values

i have an object which represents a database table. I want to iterate through this object and print printing each value. What can i use to do this?
i want to do this inside my mxml not actionscript
for each object attribute i want to create an imput field
Look up the documentation on Flex 3 looping. If you do, you'll find this:
for..in
The for..in loop iterates through the properties of an object, or the elements of an array. For example, you can use a for..in loop to iterate through the properties of a generic object (object properties are not kept in any particular order, so properties may appear in a seemingly random order):
var myObj:Object = {x:20, y:30};
for (var i:String in myObj)
{
trace(i + ": " + myObj[i]);
}
// output:
// x: 20
// y: 30
Instead of trying to create an input field for each object, I'd suggest you take a look at DataGrid and custom ItemEditors.
I agree that this answer isn't useful. It only works with generic objects, not user declared
objects.
However, here's some code that should/could work using the describeType as suggested above. (And I don't really think it's too complex). Be aware that only public properties/methods, etc. are exposed:
var ct:CustomObject = new CustomObject();
var xml:XML = describeType(ct);
for each(var accessor in xml..accessor) {
var name:String = accessor.#name;
var type.String = accessor.#type;
trace(ct[name]);
}
The problem with "for...in" is that it iterates only on dynamic properties. That is, if your object is defined as a Class (and not dynamically), "for..in" won't give anything.
The ActionScript documentation suggest to use describeType() for fixed properties, but it looks over-complicated for this simple taskā€¦
You can write it like actionscript but include it inside the mxml file with the script tag:
<mx:Script>
<![CDATA[
public function LoopAndPrint() : void
{
//your code here
}
]]>
</mx:Script>