Transformations always return new collections

Mutative methods will return the same collection reference if nothing actually changes. This is what enables strict equality change detection. Transformation methods, on the other hand, don't have this capability. This means that if a transformation method results in the exact same collection values, it still returns a new reference. Let's look at the difference between mutated collections and transformed collections:

const myList = List.of(
Map.of('one', 1, 'two', 2),
Map.of('three', 3, 'four', 4),
Map.of('five', 5, 'six', 6)
);
const myTransformedList = myList.map(v => v);
const myMutatedList = myList
.update(0, v => v.set('one', 1));

console.log('myList', myList.toJS());
// -> myList [ { one: 1, two: 2 },
// -> { three: 3, four: 4 },
// -> { five: 5, six: 6 } ]
console.log('myTransformedList', myTransformedList.toJS());
// -> myTransformedList [ { one: 1, two: 2 },
// -> { three: 3, four: 4 },
// -> { five: 5, six: 6 } ]
console.log('myMutatedList', myMutatedList.toJS());
// -> myMutatedList [ { one: 1, two: 2 },
// -> { three: 3, four: 4 },
// -> { five: 5, six: 6 } ]
console.log(
'myList === myTransformedList',
myList === myTransformedList
);
// -> myList === myTransformedList false
console.log(
'myList === myMutatedList',
myList === myMutatedList
);
// -> myList === myMutatedList true

All three of these collections—myList, myTransformedList, and myMutatedList—have identical values. When you compare myList to myTransformedList using strict equality, they don't match. This is because myTransformedList was created using map(), which is a transformation method. On the other hand, myList and myMutatedList do match when compared using strict equality. This is because update() is mutative.

If you want to compare transformed lists with their originals, you should use the equals() method:

console.log(
'myList.equals(myTransformedList)',
myList.equals(myTransformedList)
);
// -> myList.equals(myTransformedList) true
console.log(
'myList.equals(myMutatedList)',
myList.equals(myMutatedList)
);
// -> myList.equals(myMutatedList) true

This will yield consistent results, no matter how the collection was created.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.162.26