JavaScriptFundamental (ES6), part 2
Compose map and filter generators in JavaScript
8 map and filter as generators, composed
hardWrite mapG and filterG as generators and chain them with a takeG over an infinite source. Count how many source values the whole pipeline touched, and prove that building the chain does no work at all.
Stuck? Three hints, smallest first
- 1. Each stage takes an iterable and yields; the stage above pulls one value at a time through the whole chain.
- 2. Nothing runs when you build the chain. The generator objects exist, suspended, until something iterates.
- 3. Count the pulls in the source with a counter, and check it against what the pipeline needed.
function* mapG(iterable, fn) { for (const v of iterable) yield fn(v); }
function* filterG(iterable, keep) { for (const v of iterable) if (keep(v)) yield v; }
function* takeG(iterable, n) {
if (n <= 0) return;
let i = 0;
for (const v of iterable) { yield v; if (++i === n) return; }
}
let touched = 0;
function* meterReadings() {
let naira = 500;
while (true) { touched++; yield naira; naira += 500; }
}
const roundThousands = takeG(
mapG(filterG(meterReadings(), (n) => n % 1000 === 0), (n) => `₦${n}`),
3
);
const formatted = [...roundThousands];
let pulls = 0;
function* three() { for (const v of [1, 2, 3]) { pulls++; yield v; } }
const chain = mapG(three(), (n) => n * 2);
const pullsBeforeIterating = pulls;
const doubled = [...chain];
console.log('formatted :', formatted);
console.log('source touched', touched, 'times for three results');
console.log('pulls before iterating:', pullsBeforeIterating, ' after:', pulls);
console.log('second pass over the same chain:', [...chain]);
Output
7 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 7 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('the pipeline produced three formatted amounts', formatted, ['₦1000', '₦2000', '₦3000']);
test('the source was pulled exactly six times, not infinitely', touched, 6);
test('building a chain pulls nothing', pullsBeforeIterating, 0);
test('iterating it does the work, once per value', [doubled, pulls], [[2, 4, 6], 3]);
test('mapG over an array behaves the same way', [...mapG([1, 2, 3], (n) => n + 1)], [2, 3, 4]);
test('filterG can legitimately produce nothing', [...filterG([1, 3, 5], (n) => n % 2 === 0)], []);
test('an exhausted chain is empty the second time', [...chain], []);
touched === 6 is the difference between a generator pipeline and array.filter(...).map(...).slice(0, 3). The array version evaluates each stage completely before the next begins, so it allocates two intermediate arrays and, over an infinite source, never returns. The generator version interleaves: one value walks the whole chain, then the next.
Six, not three, because filterG discarded the odd half-thousands on the way. Laziness bounds the work by what the consumer asked for, it does not make the filter free.
The cost is a stack of next() calls per value, which is slower per element than an array method on small inputs. Reach for this when the input is large, infinite, or expensive to produce — a paged API, a file, a socket — and not to shave allocations off a list of ten. The last assertion is the other cost: a chain is a generator, so it is single-use, and a chain you want to reuse has to be rebuilt from a function.