Sub topic 10
Taming Infinite Sequences
This chapter assumes you know how to write generator functions with function*, and that you have already seen map, filter, take, drop, and the consuming methods such as toArray and find. Here those pieces come together on sequences that never end. You will see which pipelines finish and which hang, and how to keep them bounded.
Why Infinite Sequences Work at All
An infinite generator is a generator whose loop never exits on its own. With an array, an endless sequence is impossible, because the array would have to hold every element in memory. With an iterator, each value is produced only when someone calls next(). The sequence is endless in principle, but the program only ever computes the values it actually requests.
Iterator helpers keep this property. Each helper pulls from the iterator below it one value at a time, so the whole pipeline uses a constant amount of memory no matter how long the source is. The source code stays simple: you describe the full sequence, and you decide elsewhere how much of it to use.
function* naturals() {
let n = 0;
while (true) yield n++;
}
const result = naturals()
.filter((n) => n % 2 === 0)
.map((n) => n * n)
.take(3)
.toArray();
console.log(result); // [0, 4, 16]The generator yields only five numbers here: 0, 1, 2, 3, and 4. Once take has passed three values through, it stops asking for more, and toArray receives a finished iterator.
How the Pull Stops
The terminating method at the end of the chain drives everything. toArray keeps calling next() on take. take forwards each request to map, map forwards it to filter, and filter keeps pulling from the generator until it finds a value that passes. When take reaches its limit, it reports done: true without pulling again, and it closes the iterator beneath it.
An infinite pipeline finishes only because some stage stops pulling. The rest of this chapter turns on that one question: which stage stops pulling, and when?
Which Consumers Finish on an Infinite Source
The consuming methods split into two groups. Some must read every value before they can answer. Others can stop early once the answer is known.
| Method | Finishes on an infinite source? | Stops when |
|---|---|---|
| `toArray` | No | never, it must collect everything |
| `forEach` | No | never, unless the callback throws |
| `reduce` | No | never, the result depends on every value |
| `some` | Only if a match exists | the first value for which the predicate returns true |
| `every` | Only if a counterexample exists | the first value for which the predicate returns false |
| `find` | Only if a match exists | the first matching value |
The short-circuiting methods work directly on an endless source:
function* naturals() {
let n = 0;
while (true) yield n++;
}
console.log(naturals().find((n) => n * n > 50)); // 8
console.log(naturals().some((n) => n > 1000)); // true
console.log(naturals().every((n) => n < 10)); // falseEach call creates a fresh generator, which matters because iterators are single-use. every stops at 10, the first value that fails its test. If you called naturals().every((n) => n >= 0) instead, the predicate would never fail and the call would never return.
For toArray, forEach, and reduce, put a take before them, or they will hang.
The Filter Trap
take(n) limits how many values come out of it. It does not limit how much work happens upstream. A filter placed before take keeps pulling from the source until it finds a match. If no value ever matches, or matches become extremely rare, the program hangs even though the chain ends in take.
When you cannot be sure a match exists, bound the scan as well as the output. Put a take before the filter as well:
function* naturals() {
let n = 0;
while (true) yield n++;
}
const MAX_SCANNED = 1000;
const firstBig = naturals()
.take(MAX_SCANNED)
.filter((n) => n * n > 2_000_000)
.take(1)
.toArray();
console.log(firstBig); // [] (1415 would be the first match, beyond the scan limit)The first take caps the search at 1000 values. The second caps the result. An empty array tells you nothing matched within the budget, which is far better than a frozen process.
Order Changes the Meaning
Because take counts whatever reaches it, its position in the chain changes the result:
function* naturals() {
let n = 0;
while (true) yield n++;
}
const isEven = (n) => n % 2 === 0;
console.log(naturals().filter(isEven).take(3).toArray()); // [0, 2, 4]
console.log(naturals().take(3).filter(isEven).toArray()); // [0, 2]The first pipeline asks for "the first three even numbers." The second asks for "the even numbers among the first three naturals." Both finish, but they answer different questions. Pick the order by what you want to limit: matching results, or values inspected.
drop follows the same rule. drop(k) on an infinite source is safe, since it pulls and discards exactly k values and then passes the rest through. It still needs a take or a short-circuiting consumer somewhere below it.
Useful Infinite Sources
Many sequences are easiest to describe without an end. The Fibonacci numbers are a classic example:
function* fibonacci() {
let [a, b] = [0, 1];
while (true) {
yield a;
[a, b] = [b, a + b];
}
}
const evenFibs = fibonacci()
.filter((n) => n % 2 === 0)
.take(5)
.toArray();
console.log(evenFibs); // [0, 2, 8, 34, 144]Repeating a finite list forever is another common pattern, for example to assign colors or round-robin workers:
function* cycle(items) {
while (true) yield* items;
}
const tasks = ['parse', 'compile', 'test', 'deploy', 'notify'];
const assignments = cycle(['worker-a', 'worker-b'])
.take(tasks.length)
.map((worker, i) => `${tasks[i]} -> ${worker}`)
.toArray();
console.log(assignments);
// ['parse -> worker-a', 'compile -> worker-b', 'test -> worker-a',
// 'deploy -> worker-b', 'notify -> worker-a']Note that cycle needs a non-empty input. yield* [] yields nothing, so cycle([]) would spin forever without producing a value, and the pipeline would hang just like the filter trap.
A Checklist for Infinite Pipelines
Before running a pipeline over an endless source, check each of these:
- Something stops the pull: a
take, or a consumer such asfind,some, oreverythat can short-circuit. - Every
filterupstream of that stop is guaranteed to match eventually, or atakebefore it bounds the scan. takesits at the position that matches your intent, either before the filter to limit values inspected or after it to limit results.- Nothing in the chain, such as an empty
cycle, can loop without yielding.
If all four hold, the pipeline finishes and uses constant memory however large the source is.
Exercise
Does naturals().map((n) => n * 3).filter((n) => n % 2 === 1).take(4).toArray() finish, and if so, what does it return? Use the naturals generator from this chapter.
Show answer
It finishes. Every odd n gives an odd multiple of 3, so filter matches every other value and take receives four values quickly. The result is [3, 9, 15, 21].
Exercise
A teammate writes fibonacci().filter((n) => n % 7 === 0 && n > 1e6).toArray() to find the large Fibonacci numbers divisible by 7. Why does it hang, and how would you fix it to get the first two such numbers?
Show answer
toArray must collect every value, and the generator is infinite, so toArray never stops. Add take(2) before toArray: fibonacci().filter((n) => n % 7 === 0 && n > 1e6).take(2).toArray(). Such values exist (every eighth Fibonacci number is divisible by 7), so the filter always finds the next match. For very large values you would also need BigInt, because past about 2^53 Number loses precision and the divisibility checks become unreliable.