Sub topic 2
Limiting Output with take
This chapter assumes you know generator functions (function*) and how map and filter work on iterators. It covers the helpers that limit and skip values, the methods that produce a final result, and how combining them lets you work with sequences that never end.
Limiting Output with take
take(n) returns an iterator that yields at most n values. After that it stops, even if the source has more values. It is lazy, so it pulls only as many values from the source as it needs.
function* naturals() {
let n = 0;
while (true) yield n++;
}
console.log(naturals().take(3).toArray()); // [0, 1, 2]Skipping Values with drop
drop(n) throws away the first n values and yields everything after them. If you pair it with take, you get pagination:
function* naturals() {
let n = 0;
while (true) yield n++;
}
function page(iter, pageIndex, pageSize) {
return iter.drop(pageIndex * pageSize).take(pageSize).toArray();
}
console.log(page(naturals(), 2, 5)); // [10, 11, 12, 13, 14]The dropped values are pulled and discarded one at a time. No array is ever built to hold them.
Getting Results Out: toArray, reduce, and Friends
Helpers such as map and take return new iterators. To get an actual result, you need a consuming method, which pulls values until it is finished:
| Method | Returns |
|---|---|
| `toArray()` | Every value, in an array |
| `reduce(fn, init)` | One accumulated value |
| `forEach(fn)` | `undefined` (runs only for side effects) |
| `some(fn)` / `every(fn)` | A boolean, and it stops early once the answer is known |
| `find(fn)` | The first value that matches, then it stops |
const sum = [1, 2, 3, 4].values().reduce((a, b) => a + b, 0);
console.log(sum); // 10Building Pipelines by Chaining Helpers
Each helper wraps the one before it, so a chain makes a pipeline. Values move through it one at a time, and only when the consuming method at the end asks for them.
Taming Infinite Sequences
Because nothing runs until a value is pulled, an infinite source is safe as long as something in the chain stops it:
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]
console.log(naturals().find((n) => n > 5)); // 6Exercise
What does naturals().drop(3).take(2).toArray() return, and how many values does it pull from naturals()?
Show answer
It returns [3, 4]. It pulls five values: 0, 1, and 2 are dropped, then 3 and 4 are taken.
Exercise
Why does naturals().map((n) => n * 2).toArray() never finish?
Show answer
map does not limit its output, so toArray keeps pulling values from an infinite generator. Adding .take(n) before toArray fixes it.