
Member-only story
You may need Laziness in your Javascript (Lazy Evaluation)
Maybe some times you have overused the Array methods map, reduce, filter, find, etc. and that could make out applications to use more memory of what they should be using.
Let’s see an example:
const myArray = [1,2,3,4,5,6,7,8,9,10]myArray
.map(x => x * x)
.filter(x => x % 3 === 0)
Sure you have done something similar to this several times, and what is the “problem” here, we are creating new arrays every time we chain and array method. That means the .map creates another array with the x² in every index ([ 1, 4, 9, 16, 25, 36, 49, 64, 81, 100 ]) and after that create another filtered one [ 9, 36, 81 ] in this case you maybe don’t have any problem of performance of memory use, but what if myArray is a very large one? you are going to create another big one again, and again until you have your wanted result.
In those cases, the Lazy evaluation with iterables could be useful. But first, how can we create an iterator and how works.
What is an iterator?
An iterator is an Object that defines a sequence and maybe return a value when the sequence is finished, those sequences could be Finite or Infinite.