Reputation: 1091
I am playing around with Immutable.js code and noticed something funky. Does Immutable.js skip code that saves to variables that won't be used?
const Immutable = require('immutable')
function transformErrors(errors) {
let key = errors.keySeq()
let mapped = key.map((v, keystr) => {
console.log(v, keystr)
return keystr
})
// If I enable the console log below, console log above works
// console.log('mapped', mapped)
};
const result = transformErrors(Immutable.fromJS([1, 2]));
For the above code, if
console.log('mapped', mapped)
is disabled, the mapping code doesn't get called. I looked through the documentation but couldn't find any remarks on it
Upvotes: 1
Views: 43
Reputation: 5317
The line: let key = errors.keySeq()
will return a Seq
object, which in immutable.js is lazy.
The documentation provides the following details (https://facebook.github.io/immutable-js/docs/#/Seq):
Seq is lazy — Seq does as little work as necessary to respond to any method call. Values are often created during iteration, including implicit iteration when reducing or converting to a concrete data structure such as a List or JavaScript Array. For example, the following performs no work, because the resulting Seq's values are never iterated:
const { Seq } = require('immutable') const oddSquares = Seq([ 1, 2, 3, 4, 5, 6, 7, 8 ]) .filter(x => x % 2 !== 0) .map(x => x * x)
So in your example, immutable.js isn't going to actually evaluate your map function until mapped
is used somewhere.
Upvotes: 1