What are the ways to avoid object mutation in Dart-lang? - object

If we take the following snippet as an example:
main() {
List<int> array = [1, 2, 3, 4];
List<int> newArray = change(array);
print(array); // [99, 2, 3, 4]
print(newArray); // [99, 2, 3, 4]
print(newArray == array); // true
}
change(List<int> array) {
var newArray = array;
newArray[0] = 99;
return newArray;
}
The original array gets mutated. I was expecting that by passing the array (object) to the change function and assigning a new variable to it that I could avoid mutation. I am aware that the built_collection library seems like the main go-to for immutable collections. Is there any native way the core library that would allow for a deep freeze or prevent side effects (operations inside another function)?

You can wrap an array in an UnmodifiableListView from dart:collection and pass this around instead of the array itself. I think this is the most basic buit-in way.

Objects are passed by reference. This is by design: objects are often large data structures and internally making a copy every time an object is passed to a function can be very inefficient. (This is the same approach as that used by other major object oriented languages.)
As a result, array and newArray are two names for the same underlying List in your code.
If you want to explicitly create a new list, just change
var newArray = array;
to:
var newArray = new List.from(array);

Related

Why MongooseJS is reversing the order of properties?

I've noticed that if we insert an object {a: 1, b: 2, c: 3}, in database it'll be stored as {c: 3, b:2, a: 1}. Why is MongooseJS doing this?
Is it for Performance Gain (or) some other logic?
Could anyone please explain this to me in detail?
There is no such thing as properties order in object. If the order is important for you use an array.
The for...in statement iterates over the enumerable properties of an object, in original insertion order. For each distinct property [...]
However this seems to be implementation (browser) dependant.
In objects you can't rely on order of the properties as even various iteration methods may give various results.
Ordering of properties in objects is complex, as this answer explains: https://stackoverflow.com/a/38218582/893780
Even though it's not specified in the standard, normal property keys are stored in insertion order.
Internally, Mongoose uses a faster code path when cloning objects, that reverses the property order. It basically does this:
let oldObject = { a: 1, b: 2, c: 3 };
let newObject = {};
let keys = Object.keys(oldObject);
let i = keys.length;
while (i--) {
let k = keys[i];
let val = oldObject[k];
newObject[k] = val;
}
Because normal keys are stored in insertion order, newObject will be the reverse of oldObject:
{ c: 3, b: 2, a: 1 }
However, because this can cause issues in queries, Mongoose added an option retainKeyOrder to prevent this reversal.
However, according to the same answer that I linked to above, you still can't rely on any order being imposed when using Object.keys() or for..in.

How can I co-sort two Vecs based on the values in one of the Vecs?

I have two Vecs that correspond to a list of feature vectors and their corresponding class labels, and I'd like to co-sort them by the class labels.
However, Rust's sort_by operates on a slice rather than being a generic function over a trait (or similar), and the closure only gets the elements to be compared rather than the indices so I can sneakily hack the sort to be parallel.
I've considered the solution:
let mut both = data.iter().zip(labels.iter()).collect();
both.sort_by( blah blah );
// Now split them back into two vectors
I'd prefer not to allocate a whole new vector to do this every time because the size of the data can be extremely large.
I can always implement my own sort, of course, but if there's a builtin way to do this it would be much better.
I just wrote a crate "permutation" that allows you to do this :)
let names = vec!["Bob", "Steve", "Jane"];
let salary = vec![10, 5, 15];
let permutation = permutation::sort(&salary);
let ordered_names = permutation.apply_slice(&names);
let ordered_salaries = permutation.apply_slice(&salary);
assert!(ordered_names == vec!["Steve", "Bob", "Jane"]);
assert!(ordered_salaries == vec![5, 10, 15]);
It likely will support this in a single function call in the future.

Spock: how can I mock a list of objects which return the object I have

I have a list of objects, let it be integers:
list = [1, 3, 8]
I need a list of objects which in fact are PROVIDERS of these integers. I.e.:
providersList = [p1.getInteger() = 1, p2.getInteger() = 3, p3.getInteger() = 8] //pseudo code
How can I code it?
UPDATE
Sorry, looks like I was a little bit confusing. This is one of my first experiences with Spock so I may confuse the terms and ideas.
I want to mock a list of objects. Each object has its own methods, of course. The test will call only one method of that object. I dont need to implement it because I know what exactly returns this method. And these return values are stored in some list which I already have.
I.e. I need to mock a list of objects [p1, p2, p3] where each call to object.getInteger() returns some integer I already know, and I have a list of these integers: [i1, i2, i3]: p1.getInteger() = i1 etc.
How can I mock list of [p1, p2, p3] with the help of list [i1, i2, i3] ?
You may just try:
#Grab('org.spockframework:spock-core:0.7-groovy-2.0')
#Grab('cglib:cglib-nodep:3.1')
import spock.lang.*
class Test extends Specification {
def 'some spec'() {
given:
def mocks = [1, 2, 3].collect { i -> GroovyMock(SomeClass) {
getInteger() >> i
}
}
expect:
mocks*.getInteger().containsAll([1,2,3])
}
}
class SomeClass {
Integer getInteger() {
0
}
}

EachWithIndex groovy statement

I am new to groovy and I've been facing some issues understanding the each{} and eachwithindex{} statements in groovy.
Are each and eachWithIndex actually methods? If so what are the arguments that they take?
In the groovy documentation there is this certain example:
def numbers = [ 5, 7, 9, 12 ]
numbers.eachWithIndex{ num, idx -> println "$idx: $num" } //prints each index and number
Well, I see that numbers is an array. What are num and idx in the above statement? What does the -> operator do?
I do know that $idx and $num prints the value, but how is it that idx and num are automatically being associated with the index and contents of the array? What is the logic behind this? Please help.
These are plain methods but they follow quite a specific pattern - they take a Closure as their last argument. A Closure is a piece of functionality that you can pass around and call when applicable.
For example, method eachWithIndex might look like this (roughly):
void eachWithIndex(Closure operation) {
for (int i = 0; this.hasNext(); i++) {
operation(this.next(), i); // Here closure passed as parameter is being called
}
}
This approach allows one to build generic algorithms (like iteration over items) and change the concrete processing logic at runtime by passing different closures.
Regarding the parameters part, as you see in the example above we call the closure (operation) with two parameters - the current element and current index. This means that the eachWithIndex method expects to receive not just any closure but one which would accept these two parameters. From a syntax prospective one defines the parameters during closure definition like this:
{ elem, index ->
// logic
}
So -> is used to separate arguments part of closure definition from its logic. When a closure takes only one argument, its parameter definition can be omitted and then the parameter will be accessible within the closure's scope with the name it (implicit name for the first argument). For example:
[1,2,3].each {
println it
}
It could be rewritten like this:
[1,2,3].each({ elem ->
println elem
})
As you see the Groovy language adds some syntax sugar to make such constructions look prettier.
each and eachWithIndex are, amongst many others, taking so called Closure as an argument. The closure is just a piece of Groovy code wrapped in {} braces. In the code with array:
def numbers = [ 5, 7, 9, 12 ]
numbers.eachWithIndex{ num, idx -> println "$idx: $num" }
there is only one argument (closure, or more precisely: function), please note that in Groovy () braces are sometime optional. num and idx are just an optional aliases for closure (function) arguments, when we need just one argument, this is equivalent (it is implicit name of the first closure argument, very convenient):
def numbers = [ 5, 7, 9, 12 ]
numbers.each {println "$it" }
References:
http://groovy.codehaus.org/Closures
http://en.wikipedia.org/wiki/First-class_function
Normally, if you are using a functional programing language such as Groovy, you would want to avoid using each and eachWithIndex since they encourage you to modify state within the closure or do things that have side effects.
If possible, you may want to do your operations using other groovy collection methods such as .collect or .inject or findResult etc.
However, to use these for your problem, i.e print the list elements with their index, you will need to use the withIndex method on the original collection which will transform the collection to a collection of pairs of [element, index]
For example,
println(['a', 'b', 'c'].withIndex())
EachWithIndex can be used as follows:
package json
import groovy.json.*
import com.eviware.soapui.support.XmlHolder
def project = testRunner.testCase.testSuite.project
def testCase = testRunner.testCase;
def strArray = new String[200]
//Response for a step you want the json from
def response = context.expand('${Offers#Response#$[\'Data\']}').toString()
def json = new JsonSlurper().parseText(response)
//Value you want to compare with in your array
def offername = project.getPropertyValue("Offername")
log.info(offername)
Boolean flagpresent = false
Boolean flagnotpresent = false
strArray = json.Name
def id = 0;
//To find the offername in the array of offers displayed
strArray.eachWithIndex
{
name, index ->
if("${name}" != offername)
{
flagnotpresent= false;
}
else
{
id = "${index}";
flagpresent = true;
log.info("${index}.${name}")
log.info(id)
}
}

Sort with threads

I have an assignment and i need working code. Before i start i want to understand the problem but i cant figure out how to write it.
I have an array of data, take this for example
var arr = new byte[] {5,3,1,7,8,5,3,2,6,7,9,3,2,4,2,1}
I need to split this array in half, throw it into a thread pool and do that recursively until i have <=2 elements. If i have 2 elements i need to check which is less and put it on the left side then return the array.
What i don't understand is how do i merge the array? am i suppose to split the array, throw a thread into the pool and block until its ready? How do i get the results of the thread? I'm going to assume its not possible to merge the arrays without blocking?
Heres what i have so far.
static void Main(string[] args)
{
var arr = new byte[] { 5, 3, 1, 7, 8, 5, 3, 2, 6, 7, 9, 3, 2, 4, 2, 1 };
var newarr = Sort(arr);
Console.Write(BitConverter.ToString(newarr));
}
static byte[] Sort(byte[] arr)
{
if (arr.Length <= 2)
return arr;
if (arr.Length == 2)
{
if (arr[0] > arr[1])
{
var t = arr[0];
arr[0] = arr[1];
arr[1] = t;
}
return arr;
}
var arr1 = arr.Take(arr.Length / 2).ToArray();
var arr2 = arr.Skip(arr1.Count()).ToArray();
//??
return arr;
}
Note: The prof did say we can ask others for help. I think i can solve this without asking but i want to get the best answer. Threading is my weakness (i dont everything else, db, binary io, web interface, just never complex threads)
This appears to be a parallel version of merge sort. You should essential make it work like the recursive sequential version, but apparently run each recursive sort as a separate task.
In your task API, there should be some way to wait for completion, and perhaps to also pass results. With that, you can copy the traditional mergesort fairly well: for each sub-sort, put a task into the pool, and wait for completion of the two subtasks. Then perform the merge, and pass back your own result to your calling tasking.
If you have a regular thread API only (i.e. no real task library), then I suggest you provide the output in a third array: each thread will have two input arrays, and one output array. If you are allowed to create fresh threads for each task, you can wait for task completion by joining the two subthreads.
To add onto Martin's answer, I would not create smaller copies of the array. Instead, I would have each thread work on a subset of the original array.
More than happy to oblige: Any multi-core sorting implementation in .NET?

Resources