Sub topic 9
Building Pipelines by Chaining Helpers
This chapter assumes you already know how map, filter, take, and drop behave on their own, and that you can get results out with toArray. It also assumes you understand that iterator helpers are lazy. Here we look at what happens when you link them together: how values move through a chain, why the order of the stages matters, and how to build pipelines you can reuse.
What a Chain Actually Builds
Every helper method returns a new iterator. That new object holds a reference to the iterator it was called on. When you write source.map(f).filter(g).take(3), you get three wrapper objects nested inside each other, with the original source at the center. No callback has run yet.
const source = [1, 2, 3].values();
const mapped = source.map((n) => n * 2);
const filtered = mapped.filter((n) => n > 2);
console.log(Object.prototype.toString.call(filtered)); // [object Iterator Helper]
console.log(filtered === mapped); // false
console.log(filtered.toArray()); // [4, 6]Each stage only knows about the stage directly before it. The last stage in the chain is the only one you call next() on, directly or through a consuming method such as toArray. That call then pulls back through the chain, one stage at a time.
One Value at a Time Through the Whole Chain
Array methods process the data in batches. arr.map(f).filter(g) runs f on every element, builds a new array, and only then runs g. An iterator pipeline works the other way. A single value travels through every stage before the next value leaves the source.
The following trace makes this visible:
const log = [];
const result = [1, 2, 3, 4, 5]
.values()
.map((n) => {
log.push(`map ${n}`);
return n * 10;
})
.filter((n) => {
log.push(`filter ${n}`);
return n > 15;
})
.take(2)
.toArray();
console.log(result); // [20, 30]
console.log(log);
// ['map 1', 'filter 10', 'map 2', 'filter 20', 'map 3', 'filter 30']The map and filter entries alternate. Value 1 is mapped to 10 and rejected by the filter. Value 2 becomes 20 and passes. After 30 passes, take has its two values. On the next pull, take closes the chain instead of asking for more, so map 4 and map 5 never appear in the log.
This one-at-a-time flow brings two practical results. Memory use stays flat, because no stage keeps a list of values. Work also stops as soon as the last stage is satisfied, so expensive callbacks run only for values that are actually needed.
Order of Stages Changes the Result
Arrays and iterators share this rule: stages apply in the order you write them. With take and drop the effect is easy to miss, because these stages count the values that reach them. They do not count positions in the original source.
const data = [1, 2, 3, 4, 5, 6];
const a = data.values().filter((n) => n % 2 === 0).take(2).toArray();
const b = data.values().take(2).filter((n) => n % 2 === 0).toArray();
const c = data.values().drop(2).filter((n) => n % 2 === 0).toArray();
const d = data.values().filter((n) => n % 2 === 0).drop(2).toArray();
console.log(a); // [2, 4] first two evens
console.log(b); // [2] evens among the first two items
console.log(c); // [4, 6] evens after skipping two items
console.log(d); // [6] evens after skipping two evensThe order also changes cost even when the result stays the same. A cheap filter placed before an expensive map means the map callback runs only on values that survive the filter.
| Chain | Result | map calls for 1..10 |
|---|---|---|
| `.map(expensive).filter(isSmall)` | same values if `isSmall` checks the mapped value | 10 |
| `.filter(isCandidate).map(expensive)` | depends on `isCandidate` | only for candidates |
| `.map(expensive).take(3)` | first 3 mapped values | 3 |
| `.take(3).map(expensive)` | first 3 mapped values | 3 |
The last two rows show that take gives the same result before or after a map. Each value maps to exactly one output, so both versions return the first three mapped values. That stops being true once you add a filter.
Where the Chain Ends
A pipeline stays lazy only while every stage returns an iterator. A consuming method such as toArray, reduce, some, or find runs the pipeline and returns a plain value. After that you are no longer working with iterator helpers.
const arr = [1, 2, 3, 4].values().map((n) => n * 2).toArray();
console.log(Array.isArray(arr)); // true
// arr.take(2) would throw TypeError: arr.take is not a function
console.log(arr.slice(0, 2)); // [2, 4]A common mistake is putting toArray() in the middle of a chain to "check" the values. That forces the whole upstream into memory, and it fails outright on an infinite source. Put the consuming method last, or debug with a pass-through stage like the one shown below.
Reusable Stages
A stage is a function from iterator to iterator, which makes stages easy to name and combine. A small pipe function applies them in order:
function pipe(source, ...stages) {
return stages.reduce((it, stage) => stage(it), source);
}
const evens = (it) => it.filter((n) => n % 2 === 0);
const squares = (it) => it.map((n) => n * n);
const first = (k) => (it) => it.take(k);
const tap = (label) => (it) =>
it.map((value) => {
console.log(label, value);
return value;
});
const out = pipe(
[1, 2, 3, 4, 5, 6, 7, 8].values(),
evens,
tap('even'),
squares,
first(3)
).toArray();
console.log(out); // [4, 16, 36]The tap stage logs each value and passes it through unchanged. Because of laziness, it logs only the values the downstream stages actually pull: 2, 4, and 6. The 8 never appears. Use this to see what a pipeline is really doing without breaking its laziness.
Branching From a Shared Source
A chain is a straight line. If you build two pipelines on the same source iterator, they do not each get a copy of the data. They compete for it.
const src = [1, 2, 3, 4].values();
const doubled = src.map((n) => n * 2);
const tripled = src.map((n) => n * 3);
console.log(doubled.next().value); // 2 (took 1 from src)
console.log(tripled.next().value); // 6 (took 2 from src)
console.log(doubled.next().value); // 6 (took 3 from src)If you need two independent views, create two sources, for example by calling .values() twice on the array or by calling the generator function twice. If the source can only be read once, collect it into an array first.
Exercises
Exercise
What does this log, and how many times does the map callback run? const r = [5, 10, 15, 20, 25].values().drop(1).map((n) => n / 5).filter((n) => n % 2 === 1).take(1).toArray(); console.log(r);
Show answer
It logs [3]. drop(1) skips 5. The map callback runs on 10, which gives 2 and is rejected. It runs on 15, which gives 3 and passes, so take(1) is satisfied. On the next pull, take closes the chain without asking for another value. The map callback runs twice.
Exercise
You need the first 5 even numbers greater than 100 from a generator naturals(). Rewrite naturals().take(5).filter((n) => n > 100 && n % 2 === 0).toArray() so it works, and explain why the original returns the wrong result.
Show answer
Use naturals().filter((n) => n > 100 && n % 2 === 0).take(5).toArray(), which returns [102, 104, 106, 108, 110]. The original takes the first 5 naturals (0 through 4) before filtering, so nothing passes and it returns []. Because take counts the values that reach it, it has to come after the filter.
Exercise
Write a reusable stage skipThenTake(skip, count) that works with the pipe function in this chapter, and use it to get [30, 40] from [10, 20, 30, 40, 50].values().
Show answer
const skipThenTake = (skip, count) => (it) => it.drop(skip).take(count); and then pipe([10, 20, 30, 40, 50].values(), skipThenTake(2, 2)).toArray() returns [30, 40].