Sub topic 6
Limiting Output with take
This chapter assumes you already know the iteration protocol (next() returning { value, done }), generator functions, and the idea from earlier chapters that iterator helpers are lazy. You will learn what take does, how many values it pulls from its source, when it stops the source, and which edge cases catch people out.
What take does
Iterator.prototype.take(limit) returns a new iterator that yields at most limit values from the iterator it is called on, then reports done: true. If the source runs out first, take ends early without complaint.
const firstThree = [10, 20, 30, 40, 50].values().take(3);
console.log([...firstThree]); // [10, 20, 30]
const short = [10, 20].values().take(5);
console.log([...short]); // [10, 20]The array version of this would be slice(0, 3). The two differ in an important way. slice needs the whole array to exist already. take works on a source that produces values on demand, and it asks that source for only as many values as it needs.
How many values take pulls
Like the other helpers, calling take runs no code in the source. Work happens only when someone calls next() on the result. This example logs every value the source produces:
function* noisy() {
for (let i = 1; i <= 5; i++) {
console.log('source yields', i);
yield i;
}
}
const firstTwo = noisy().take(2);
console.log('created');
console.log(firstTwo.next());
console.log(firstTwo.next());
console.log(firstTwo.next());
// created
// source yields 1
// { value: 1, done: false }
// source yields 2
// { value: 2, done: false }
// { value: undefined, done: true }The third call does not print source yields 3. When the count of remaining values reaches zero, take does not ask the source for one more value to throw away. It stops. With take(n), the source's next() runs at most n times.
This matters when the source is expensive, such as a generator that reads from disk, or one with side effects. It also means callbacks earlier in the chain run only for the values that get through:
let calls = 0;
const result = [1, 2, 3, 4, 5, 6].values()
.map((x) => {
calls++;
return x * 10;
})
.take(2)
.toArray();
console.log(result); // [10, 20]
console.log(calls); // 2The eager version, [1, 2, 3, 4, 5, 6].map(...).slice(0, 2), would run the callback six times.
The algorithm inside take
Each call to next() on a take iterator follows the same steps. The diagram shows them.
Two details in this loop are worth knowing.
First, the check for remaining === 0 comes before any pull. That is why the source runs at most n times.
Second, take closes the source by calling its return() method. The next section shows exactly when that happens.
When the source gets closed
take closes the source on the call to next() after the last allowed value, not at the moment it hands that value out. You can watch this with a generator that has a finally block:
function* source() {
try {
yield 'a';
yield 'b';
yield 'c';
} finally {
console.log('source closed');
}
}
const it = source().take(2);
console.log(it.next().value); // a
console.log(it.next().value); // b
console.log('limit reached, source still open');
console.log(it.next());
// source closed
// { value: undefined, done: true }Consuming methods such as toArray and spread keep calling next() until they see done: true, so they always trigger that final call, and cleanup happens. If you call next() by hand exactly n times and then walk away, the source stays suspended inside its try block and the finally never runs. A for...of loop that exits with break avoids this problem, because the loop calls return() on the take iterator, and take passes the call on to the source. The chapter on early termination covers return() propagation in full.
Edge cases of the limit argument
take converts its argument to a number, truncates it toward zero, and checks it straight away, when take is called and before any value is pulled.
| Call | Effective limit | Result |
|---|---|---|
| `take(3)` | 3 | Up to 3 values |
| `take(2.9)` | 2 | Fraction is truncated |
| `take('2')` | 2 | String is converted to a number |
| `take(0)` | 0 | Empty; source is closed on the first `next()` |
| `take(Infinity)` | Infinity | No limit; passes every value through |
| `take(-1)` | none | Throws `RangeError` immediately |
| `take(NaN)` or `take()` | none | Throws `RangeError` immediately |
Calling take() with no argument is a common mistake. undefined converts to NaN, so you get a RangeError and not an unlimited iterator. If you want "no limit" to be an option, pass Infinity explicitly:
function firstN(iter, n = Infinity) {
return iter.take(n);
}
console.log(firstN([1, 2, 3].values()).toArray()); // [1, 2, 3]
console.log(firstN([1, 2, 3].values(), 1).toArray()); // [1]take(0) is valid and occasionally useful as a placeholder in conditional pipelines. On the first next() it closes the source without pulling from it. A generator source that was never started gets closed before its body runs, so not even its finally block executes.
function* gen() {
console.log('body started');
yield 1;
}
console.log(gen().take(0).toArray()); // []
// "body started" is never printedtake is what makes infinite sources safe
Any generator built on while (true) needs something to bound it before you call a consuming method such as toArray. take is the usual choice:
function* ids() {
let id = 1000;
while (true) yield `user-${id++}`;
}
console.log(ids().take(3).toArray());
// ['user-1000', 'user-1001', 'user-1002']Where you put take in a chain changes the meaning. filter(...).take(3) gives the first three values that pass the filter. take(3).filter(...) looks at only the first three source values and may return fewer. On an infinite source, filter(...).take(3) finishes only if three matches eventually show up. If the filter can never match three times, the pipeline loops forever. The chapter on infinite sequences covers these patterns in more depth.
Exercise
Given function* g() { try { yield 1; yield 2; yield 3; } finally { console.log('done'); } }, what does this print: const it = g().take(2); console.log(it.next().value); console.log(it.next().value); console.log([...it]);? Explain when "done" appears.
Show answer
It prints 1, then 2, then "done", then []. The first two next() calls return the two allowed values while the generator stays suspended. The spread makes one more next() call. Because remaining is now 0, take calls return() on the generator, which runs its finally block and logs "done". Then take reports done: true, so the spread produces an empty array.
Exercise
A colleague writes const limit = config.max; items.values().take(limit).toArray(); and it throws a RangeError whenever config.max is missing. Why, and how would you fix it?
Show answer
When config.max is missing, limit is undefined. take converts undefined to NaN and throws a RangeError for NaN as soon as it is called. Supply a default such as take(config.max ?? Infinity) so a missing value means no limit.
Exercise
How many times does the map callback run in [1, 2, 3, 4, 5, 6, 7, 8].values().map(f).filter((x) => x % 2 === 0).take(2).toArray() if f is (x) => x + 1?
Show answer
Three times. map turns 1 into 2 (passes the filter, first value), 2 into 3 (rejected), and 3 into 4 (passes, second value). After the second value, take's remaining count is 0, so the next pull closes the chain without asking map for another value.