Due to the logic of the card and the filter regarding lazy sequence estimation
map
last (), called on the displayed sequence, returns the last () of the original sequence processed by the matching function.
So for example:
var mappedSequence = Immutable.Sequence(1,2,3,4,5,6,7,8).map(x => x * x); console.log(mappedSequence.last());
It will output 64 and output the card only once , because the only thing it does is get the last element of the original sequence (8) and map it to x => x * x (resulting in 64)
filter
last (), called by the filtered sequence, will reverse the sequence until it finds a value in sequnce that matches the criteria. So for example
var mappedSequence = Immutable.Sequence(1,2,3,4,5,6,7,8).filter(x => x % 2); console.log(mappedSequence.last());
The output is WIll 7 and will only call the filter twice because it first calls the filter (x => x% 2) for 8, it returns 0, which means false for javascript (so it should be filtered), and then call the filter function again. to get 7% 2 = 1, which is true for javascript, and return this value as the last without the functoin filter function anymore.
As an additional example, to help understand:
var mappedSequence = Immutable.Sequence(1,2,3,4,6,8).filter(x => x % 2); console.log(mappedSequence.last());
Call the filter function four times , one for 8 (total false), one for 6 (false again), one for 4 (false again) and finally for 3 (finally, the result is true)
Combining both parts
Your example:
var oddSquares = Immutable.Sequence(1,2,3,4,5,6,7,8) .filter(x => x % 2).map(x => x * x); console.log(oddSquares.last());
- To get the last () value of the displayed sequence, you first need to get the last () value of the filtered sequence
- To get the last () value of the filtered sequence, first get the last () value of the original sequence (8) and evaluate its filter function again (x => x% 2) , calling it for the first time
- Since 8% 2 = 0, it is incorrect for JS and should be filtered out, so we go to the next value (7) and call the filter function with this value again
- 7% 2 = 1, this is true for JS and should NOT be filtered, so this is the last value of the filtered sequence
- We have the last value (7) needed for the displayed sequence, so we call the display function (x => x * x) only once to get 49, the final result
In the end, we get the filter function two times , and the display function only once