Sub topic 14
Lazy and Infinite Sequences and Pipelines
This chapter assumes you can write generator functions, know that a generator's body runs only when next() is called, and know that leaving a for...of early calls the iterator's return().
Lazy means "compute on demand"
An array is eager. Every element exists in memory before you touch the first one. A generator is lazy: it computes each value only when a consumer calls next(), and then it pauses. Laziness gives you two practical benefits:
- You can describe sequences with no end, such as all natural numbers, because only the values you ask for are ever computed.
- You can chain processing steps without building intermediate arrays. Each value passes through the whole chain before the next value is produced.
An infinite source
This generator never finishes:
function* naturals() {
let n = 0;
while (true) yield n++;
}The while (true) loop is safe because yield suspends the function each time. The loop continues only when someone asks for another value. Spreading it with [...naturals()] would hang, though, because spread keeps pulling until done: true, and that never comes.
Building a pipeline
A pipeline stage is a generator that takes an iterable, pulls from it, and yields transformed values. Because each stage is iterable too, you can nest stages:
function* naturals() {
let n = 0;
while (true) yield n++;
}
function* map(iterable, fn) {
for (const x of iterable) yield fn(x);
}
function* take(iterable, k) {
if (k <= 0) return;
for (const x of iterable) {
yield x;
if (--k === 0) return;
}
}
console.log([...take(map(naturals(), n => n * n), 4)]); // [ 0, 1, 4, 9 ]Read the call from the inside out: naturals() feeds map, and map feeds take. Execution actually runs from the outside in. Spread asks take for a value, take asks map, map asks naturals, and one number travels back up the chain.
Why `take` must stop the chain
When take reaches its limit, it executes return inside its for...of. Leaving the loop early calls return() on the map generator. That generator is paused inside its own for...of, so the call closes naturals as well. The infinite source never computes more values than take asked for.
Common errors
| Mistake | Result |
|---|---|
| Spreading or calling `Array.from` on an infinite generator | The program hangs and memory grows without limit |
| Putting a "collect everything" stage before `take` | The program hangs |
| Writing `take` so it pulls one extra value before stopping | One more value than needed is computed, which matters if that value is expensive or has side effects |
The take above checks the count right after yielding, so it never pulls the extra value.
Exercise
Write a filter(iterable, pred) stage and use it to get the first three even squares from naturals(). Which order of stages works?
Show answer
Define function* filter(iterable, pred) { for (const x of iterable) if (pred(x)) yield x; } and call [...take(filter(map(naturals(), n => n * n), x => x % 2 === 0), 3)], which gives [ 0, 4, 16 ]. take must be the outermost stage. If take ran first and filter came after it, filter would see only the first few squares and could return fewer than three even values.
Exercise
Why does [...map(naturals(), n => n + 1)] never finish, while for (const x of map(naturals(), n => n + 1)) { if (x > 3) break; } finishes?
Show answer
Spread pulls until done: true, and an infinite generator never reports it. The for...of loop leaves through break, which calls return() on map, and that closes naturals.