Sub topic 14
Lazy and Infinite Sequences and Pipelines
This chapter assumes you are comfortable with generator functions, yield, yield*, and the way for...of calls return() when a loop exits early. All of these were covered in earlier chapters. Here you will use generators to describe sequences that compute values only on request. Some of those sequences never end, and you will chain them into pipelines.
Eager Versus Lazy Evaluation
Array methods are eager. arr.map(f).filter(g).slice(0, 3) runs f on every element and builds a full intermediate array. It then runs g on every element of that array and builds a second one. Only after all that does it keep three items.
A generator is lazy. It computes nothing until a consumer calls next(), and each call computes one value. A chain of generators therefore does exactly as much work as the final consumer asks for.
| Aspect | Eager (array methods) | Lazy (generator pipeline) |
|---|---|---|
| When work happens | Immediately, for every element | On each `next()` call, one value at a time |
| Intermediate storage | A new array per stage | None; values pass through one by one |
| Infinite sources | Impossible | Fine, as long as something limits consumption |
| Reusable result | Yes, arrays can be iterated many times | No, the pipeline is a one-shot iterator |
| Operations needing all data (sort, reverse) | Natural | Require collecting everything first |
An Infinite Source
An infinite sequence is a generator whose loop never exits by itself:
function* naturals() {
let n = 0;
while (true) yield n++;
}
const it = naturals();
console.log(it.next().value); // 0
console.log(it.next().value); // 1
console.log(it.next().value); // 2The while (true) loop is safe because each yield suspends the generator. The loop advances only when someone asks for the next value.
Building Pipeline Stages
A pipeline stage is a generator that takes an iterable, pulls values from it, and yields transformed values. Because a stage both consumes and produces iterables, stages compose:
function* naturals() {
let n = 0;
while (true) yield n++;
}
function* map(iterable, fn) {
for (const x of iterable) yield fn(x);
}
function* filter(iterable, pred) {
for (const x of iterable) {
if (pred(x)) yield x;
}
}
function* take(iterable, k) {
if (k <= 0) return;
for (const x of iterable) {
yield x;
if (--k === 0) return;
}
}
const evensSquared = take(
map(filter(naturals(), n => n % 2 === 0), n => n * n),
4
);
console.log([...evensSquared]); // [ 0, 4, 16, 36 ]Read the nesting from the inside out: start with all naturals, keep the even ones, square them, and stop after four. Without take, the spread would never finish.
take is the stage that makes infinite pipelines safe. Two details in it matter:
- The
if (k <= 0) return;guard stops the generator before it pulls anything, sotake(src, 0)never touches the source. - The check comes after
yield. As soon as the last wanted value has been handed out,takereturns without asking the source for one more.
Watching the Pull Model
The consumer at the end drives the whole pipeline. Each next() on the outermost stage causes a chain of next() calls down to the source, and one value travels back up.
You can see this order by adding logs:
function* naturals() {
let n = 0;
try {
while (true) {
console.log('produce', n);
yield n++;
}
} finally {
console.log('source closed');
}
}
function* map(iterable, fn) {
for (const x of iterable) {
console.log('map', x);
yield fn(x);
}
}
function* take(iterable, k) {
if (k <= 0) return;
for (const x of iterable) {
yield x;
if (--k === 0) return;
}
}
for (const v of take(map(naturals(), n => n * n), 2)) {
console.log('got', v);
}
// produce 0
// map 0
// got 0
// produce 1
// map 1
// got 1
// source closedEach value goes through every stage before the next value is produced. No stage runs ahead of the others.
The output also shows how cleanup works. When take returns from inside its for...of, that loop calls return() on the map generator. The for...of inside map then calls return() on naturals, and the finally block in naturals runs. Closing the outer stage closes every stage below it. This is why stages should use for...of instead of calling next() by hand: the loop handles early-exit cleanup for you.
Gotcha: Pulling One Too Many
A small change to take makes it do extra work:
function* naturals() {
let n = 0;
while (true) {
console.log('produce', n);
yield n++;
}
}
function* takeEager(iterable, k) {
for (const x of iterable) {
if (k-- <= 0) return; // checks before yielding
yield x;
}
}
console.log([...takeEager(naturals(), 2)]);
// produce 0
// produce 1
// produce 2 <- computed and thrown away
// [ 0, 1 ]This version learns that it is finished only after it has pulled the next value. With cheap numbers, that is harmless. With a source that reads a file, queries a database, or prompts a user, the extra pull is a real side effect. Decide whether to stop before you go back to the source.
Stopping on a Condition
Sometimes the limit is a condition rather than a count. takeWhile yields values until a predicate fails:
function* fibonacci() {
let [a, b] = [0, 1];
while (true) {
yield a;
[a, b] = [b, a + b];
}
}
function* takeWhile(iterable, pred) {
for (const x of iterable) {
if (!pred(x)) return;
yield x;
}
}
console.log([...takeWhile(fibonacci(), n => n < 100)]);
// [ 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 ]takeWhile has to pull one value past the end, because it can only test a value after it has that value. This extra pull cannot be avoided, unlike the one in takeEager.
Making Pipelines Readable
Nested calls read inside out. A small pipe helper lets you list the stages in order:
function* naturals() {
let n = 0;
while (true) yield n++;
}
const map = fn => function* (it) { for (const x of it) yield fn(x); };
const filter = pred => function* (it) { for (const x of it) if (pred(x)) yield x; };
const take = k => function* (it) {
if (k <= 0) return;
for (const x of it) { yield x; if (--k === 0) return; }
};
const pipe = (source, ...stages) => stages.reduce((it, stage) => stage(it), source);
const result = pipe(
naturals(),
filter(n => n % 3 === 0),
map(n => `#${n}`),
take(3)
);
console.log([...result]); // [ '#0', '#3', '#6' ]Each stage factory returns a generator function that waits for its input iterable. The next chapter covers the built-in iterator helper methods, which give you map, filter, take, and more as methods you can chain, so you do not need to write these stages yourself.
When Laziness Is the Wrong Choice
- You need all the data anyway. Sorting, reversing, grouping, and finding a maximum must see every element, so a lazy pipeline gains nothing at that step.
- You iterate more than once. A pipeline is a one-shot iterator. Collect it into an array if you need several passes.
- The work is small and the data is finite. Plain array methods are simpler and usually fast enough.
- Timing of side effects matters. Lazy stages run their callbacks only when values are pulled. A
mapcallback that logs or writes data runs when the pipeline is consumed, not when it is built.
Exercise
Given the generator stages from this chapter, how many times does naturals() produce a value when you run [...take(filter(naturals(), n => n > 5), 2)]? What is the result?
Show answer
The result is [ 6, 7 ]. naturals produces 0 through 7, which is eight values. filter discards 0 to 5, passes 6 and 7, and take returns immediately after yielding 7 without pulling again.
Exercise
Write a generator stage chunk(iterable, size) that yields arrays of up to size consecutive items, so that [...chunk(take(naturals(), 5), 2)] gives [ [0, 1], [2, 3], [4] ]. It must work lazily on infinite input.
Show answer
function* chunk(iterable, size) { let buf = []; for (const x of iterable) { buf.push(x); if (buf.length === size) { yield buf; buf = []; } } if (buf.length > 0) yield buf; }. Each chunk is yielded as soon as it fills, so chunk works on infinite sources. The final partial chunk is yielded only when the source finishes.
Exercise
Why does the 'source closed' message appear in the logging example even though nothing calls return() on naturals() directly?
Show answer
When take returns from inside its for...of, that loop calls return() on the map generator. That closes map's own for...of over naturals, which calls return() on naturals and runs its finally block. Early exit passes down through every stage.