JavaScriptFundamental (ES6), part 1
Lazy zip over iterables in JavaScript
128 zip, and why a lazy chain touches fewer elements
hardWrite zip over two iterables, stopping at the shorter one. Then run the same three-step job twice — uppercase, keep the long names, take two — once as an array chain and once as a generator chain, counting how many times the first step runs each way. Finally show the value zip quietly swallows from the longer side.
Stuck? Three hints, smallest first
- 1. Take the iterators yourself with
[Symbol.iterator]()and step them together;for...ofcan only drive one. - 2. Count with a side effect in the mapping function. The array version maps the whole array before
filterever sees a value. - 3. When one side is done,
ziphas already pulled from the other — that value has nowhere to go.
function* naturals(from = 1) {
let n = from;
while (true) {
yield n;
n += 1;
}
}
function* map(source, fn) {
for (const value of source) yield fn(value);
}
function* filter(source, ok) {
for (const value of source) if (ok(value)) yield value;
}
function* take(source, count) {
if (count <= 0) return;
let taken = 0;
for (const value of source) {
yield value;
taken += 1;
if (taken >= count) return;
}
}
function* zip(left, right) {
const a = left[Symbol.iterator]();
const b = right[Symbol.iterator]();
while (true) {
const x = a.next();
const y = b.next();
if (x.done || y.done) return;
yield [x.value, y.value];
}
}
const toArray = (source) => [...source];
const stops = ['Oshodi', 'Ikeja', 'Yaba', 'Surulere', 'Ojota', 'Ketu', 'Mile 12', 'Berger'];
let eagerTouches = 0;
const eager = stops
.map((s) => { eagerTouches += 1; return s.toUpperCase(); })
.filter((s) => s.length > 4)
.slice(0, 2);
let lazyTouches = 0;
const lazy = toArray(take(
filter(map(stops, (s) => { lazyTouches += 1; return s.toUpperCase(); }), (s) => s.length > 4),
2,
));
const numbered = toArray(map(zip(naturals(), stops), ([i, name]) => `${i}. ${name}`));
const uneven = toArray(zip([1, 2, 3], ['a', 'b']));
const counter = naturals();
const shortPairs = toArray(zip(counter, ['a', 'b']));
const nextFromCounter = counter.next().value;
console.log('eager :', eager, '| touched', eagerTouches);
console.log('lazy :', lazy, '| touched', lazyTouches);
console.log('zip :', numbered.slice(0, 3), '| uneven:', uneven);
Output
8 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 8 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('both chains give the same answer', [eager, lazy], [['OSHODI', 'IKEJA'], ['OSHODI', 'IKEJA']]);
test('the array chain maps all eight; the generator chain maps two', [eagerTouches, lazyTouches], [8, 2]);
test('zip numbers a finite list against an endless counter', numbered.slice(0, 3), ['1. Oshodi', '2. Ikeja', '3. Yaba']);
test('and stops when the finite side runs out', numbered.length, 8);
test('with unequal lengths it stops at the shorter one', uneven, [[1, 'a'], [2, 'b']]);
test('but it had already pulled a third value from the longer side', [shortPairs.length, nextFromCounter], [2, 4]);
test('an endless source is harmless as long as something bounds it', toArray(take(naturals(9), 3)), [9, 10, 11]);
test('the array chain builds two throwaway arrays; the lazy one builds none', [Array.isArray(stops.map((s) => s)), Array.isArray(map(stops, (s) => s))], [true, false]);
The count is the lesson. map().filter().slice() does every step to every element before the next step starts, so eight names are uppercased to keep two, and two intermediate arrays are allocated on the way. The generator chain runs the steps per element and stops as soon as take is satisfied: two names touched, no intermediate arrays. On eight strings this is invisible; on a hundred thousand rows where the first step is expensive, it is the difference between the two designs.
Laziness is not free. Generators have per-value overhead, so for small arrays where you want everything anyway, the array chain is usually faster as well as clearer. Reach for the lazy version when the source is large, endless, or expensive per element, or when you genuinely need only the first few results.
zip hides a real cost: to discover that one side is finished it has to ask, and by then it has already taken a value from the other side and has nothing to pair it with. The assertion catches it — the counter is sitting on 4 after only two pairs came out. If the other side is a network cursor or a queue, that value is gone. Zipping with a lookahead, or checking the shorter side first, is the fix when it matters.