Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 1

Write iterator helpers by hand in JavaScript

127 iterator helpers, written by hand

hard

Write map, filter and take as generators over any iterable, plus a pipeline that threads a source through them. Pull four values out of an endless counter, prove that the mapping function ran only as many times as values were needed, that a consumed pipeline is empty the second time, and that stopping early still runs a source's finally.

Stuck? Three hints, smallest first
  1. 1. Each helper is three lines: for (const v of source) yield .... Because it is a generator, nothing runs until someone pulls.
  2. 2. take is the only one that needs a counter, and it must return rather than break so the count is checked after the yield.
  3. 3. Never spread an endless generator. Something in the chain has to be a take, or the loop guard is your only protection — and for...of is not guarded at all.

The answer

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;
  }
}

const toArray = (source) => [...source];
const pipeline = (source, ...steps) => steps.reduce((acc, step) => step(acc), source);

const everyThirdInKobo = toArray(pipeline(
  naturals(),
  (s) => filter(s, (n) => n % 3 === 0),
  (s) => map(s, (n) => n * 100),
  (s) => take(s, 4),
));

let squareCalls = 0;
const threeSquares = toArray(take(map(naturals(), (n) => { squareCalls += 1; return n * n; }), 3));

const once = take(naturals(), 3);
const firstDrain = toArray(once);
const secondDrain = toArray(once);

let closed = false;
function* readings() {
  try {
    yield 1;
    yield 2;
    yield 3;
  } finally {
    closed = true;
  }
}
const twoOfThree = toArray(take(readings(), 2));

console.log('pipeline :', everyThirdInKobo);
console.log('lazy     :', threeSquares, '| the mapper ran', squareCalls, 'times');
console.log('drains   :', firstDrain, secondDrain, '| source closed:', closed);

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.

8 checks

test('four multiples of three, in kobo, out of an endless counter', everyThirdInKobo, [300, 600, 900, 1200]);
test('the mapper ran once per value taken, not once per value available', [threeSquares, squareCalls], [[1, 4, 9], 3]);
test('take past the end of a finite source just stops', toArray(take(['Yaba', 'Ketu'], 5)), ['Yaba', 'Ketu']);
test('taking none pulls nothing at all', toArray(take(naturals(), 0)), []);
test('the helpers accept any iterable, a string or a Set included', [toArray(take('Lagos', 3)), toArray(map(new Set([1, 2, 2, 3]), (n) => n * 2))], [['L', 'a', 'g'], [2, 4, 6]]);
test('a generator is a one-shot: the second drain finds it empty', [firstDrain, secondDrain], [[1, 2, 3], []]);
test('stopping early still gives the source its cleanup', [twoOfThree, closed], [[1, 2], true]);
test('and each helper hands back an iterator, not an array', [Array.isArray(map([1], (n) => n)), typeof map([1], (n) => n)[Symbol.iterator]], [false, 'function']);

Three generators and a reduce give you a lazy pipeline. The shape to notice is that none of the helpers has a loop that drives anything — for (const v of source) yield pulls exactly one value per value requested, so the consumer at the end of the chain sets the pace. That is what makes an endless source usable at all.

take is where the care goes. Counting after the yield and returning means the count is checked when the consumer comes back for more, so take(s, 3) pulls three values and no fourth. And return inside a for...of is not just an exit: it calls the source iterator's return(), which resumes the source generator with a return completion and runs its finally. That is how a lazy read of a file or a cursor gets closed when you stop halfway, and it is the assertion above about closed.

The one-shot assertion is the trap people meet in practice. A generator is an iterator, so it is its own Symbol.iterator and draining it consumes it: pass a pipeline to two functions and the second gets nothing. Arrays are re-iterable; iterators are not. If you need two passes, materialise with toArray or build the pipeline twice from a factory. JavaScript now ships Iterator.prototype.map, filter, take and drop that do all this natively, with exactly these semantics.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.