Sub topic 9
Building Pipelines by Chaining Helpers
This chapter assumes you know map, filter, take, and drop on their own. It also assumes you know that helpers are lazy and that methods such as toArray consume an iterator. Here we combine those pieces.
Each Helper Returns an Iterator
Every helper returns a new iterator helper object. That object also inherits from Iterator.prototype, so you can call another helper on it. A chain like .filter().map().take() builds a stack of iterators, and each one wraps the one before it.
Building the chain does no work. The work starts only when a consuming method such as toArray, reduce, or a for...of loop asks the last stage for a value.
One Value at a Time
Array methods finish one whole step before the next step starts. A pipeline instead moves each value through every stage before it reads the next value. Logging makes this order visible:
const log = [];
const out = [1, 2, 3, 4, 5]
.values()
.filter((n) => {
log.push(`filter ${n}`);
return n % 2 === 1;
})
.map((n) => {
log.push(`map ${n}`);
return n * 10;
})
.take(2)
.toArray();
console.log(out); // [10, 30]
console.log(log);
// ['filter 1', 'map 1', 'filter 2', 'filter 3', 'map 3']The values 4 and 5 are never read. After take has passed on two values, it stops pulling and closes the chain behind it.
Order Matters
Each stage only sees what the stage before it produces. Swapping two stages can change the result:
const nums = () => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].values();
console.log(nums().drop(2).take(3).toArray()); // [3, 4, 5]
console.log(nums().take(3).drop(2).toArray()); // [3]Order also affects cost. If you put filter before an expensive map, the map callback runs only on the values that pass the filter.
Common Errors
| Mistake | Symptom | Fix |
|---|---|---|
| Building a chain but never consuming it | Callbacks never run | End with `toArray`, `forEach`, `reduce`, or a loop |
| Putting `map` before `filter` when the filter uses the original value | Filter tests the transformed value | Reorder the stages or adjust the predicate |
| Calling `take` before `drop` when you want a page of results | Fewer items than expected | Use `drop(offset).take(size)` |
Exercise
What does this print, and which values does the map callback receive? console.log([5, 6, 7, 8, 9].values().drop(1).map((n) => n * 2).filter((n) => n > 13).take(1).toArray());
Show answer
It prints [14]. drop skips 5. The map callback receives 6, which becomes 12 and fails the filter. It then receives 7, which becomes 14, passes the filter, and fills the take limit. The map callback runs only for 6 and 7. The values 8 and 9 are never pulled.
Exercise
You need the first 3 squares of the even numbers in a large array, and squaring is expensive. Should map or filter come first, and why?
Show answer
filter should come first: arr.values().filter((n) => n % 2 === 0).map((n) => n * n).take(3).toArray(). That way the square is computed only for even numbers, and only until take has three results.