Sub topic 6
Limiting Output with take
This chapter assumes you know generator functions, the next() protocol, and the lazy pull model from the earlier chapters. take(n) is the helper that lets a pipeline stop. It returns a new iterator that yields at most n values from its source and then reports done: true.
The basic shape
take is lazy, like map and filter. Calling it does no work. Work happens only when a consumer such as toArray() or for...of pulls values. Each pull through take makes exactly one pull from the source, and only while the limit allows it.
function* naturals() {
let n = 0;
while (true) {
console.log('produce', n);
yield n++;
}
}
const firstThree = naturals().take(3);
console.log('created');
console.log(firstThree.toArray());
// created
// produce 0
// produce 1
// produce 2
// [0, 1, 2]The generator never logs produce 3. After take has handed out three values, the next pull does not reach the source. take closes the source and finishes. This is why toArray() can safely follow an infinite generator once take sits between them.
Position in the chain matters
take counts the values that reach it. It does not count the values its source looked at. If you put it before or after filter, you get different results:
const nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const isEven = (n) => n % 2 === 0;
console.log(nums.values().take(5).filter(isEven).toArray()); // [2, 4]
console.log(nums.values().filter(isEven).take(5).toArray()); // [2, 4, 6, 8, 10]The first pipeline means "of the first five numbers, keep the even ones." The second means "give me the first five even numbers." Read a pipeline from left to right and ask what take actually receives.
Common errors
| Mistake | What happens |
|---|---|
| Calling `take` on an array | `TypeError`, because arrays have no `take`. Use `.values()` first. |
| `take(-1)` or `take(NaN)` | `RangeError`, thrown at once when you call `take`. |
| `take(0)` | Valid. It yields nothing and closes the source on the first pull. |
| `take(Infinity)` | Valid. It applies no limit, so an infinite source never ends. |
A later chapter covers the validation rules and the cleanup that take triggers through return() in more detail.
Exercise
Given function* g() { let i = 0; while (true) yield i++; }, what does g().map((x) => x * 10).take(2).toArray() return, and how many times does the map callback run?
Show answer
It returns [0, 10]. The map callback runs exactly twice. take(2) pulls only two values through map, and on the third pull it closes the source without asking map for another value.
Exercise
You want the first three numbers greater than 100 from an infinite generator. Should take go before or after filter?
Show answer
After filter: gen().filter((n) => n > 100).take(3). If take came first, it would limit the raw values to three, and none of those three might pass the filter.