[ES2024] Make JavaScript computations lazy using Iterator Helpers

Zhentiw發表於2024-05-22

You no longer need to write generator functions to create basic lazy iterator functions.

Now, ECMAScript supports iterator helpers that you can call on Array.values(). With these helpers, the values of an array will be operated on lazily, and will only run when the values are needed.

Previously:

function* lazyMap(iterable, mapperFn) {
  for (let item of iterable) {
    yield mapperFn(item)
  }
}

var arr = [1,2,3,4,5]
var iter = lazyMap(arr, x => x **2)

console.log([...iter]) // [1, 4, 9, 16, 25]

With helper: values()

var arr = [1,2,3,4,5]
var iter = arra.values().map(x => x **2)

console.log([...iter])

Why use lazy iterator?

If the array size if huge, when you do .map, .filter, .reduceyou have to read the whole array and also copy a new array... with iterator, we can read whenever when you need it.

相關文章