Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 1

Lazy evaluation with generators in JavaScript

101 a lazy pipeline over an endless sequence

hard

Write generator versions of map and filter, plus take(n, iterable), and run them over a generator that never ends. Take the first four squares of the multiples of three, then count how many source values were actually pulled. Show that an iterator is single-use and that any object can join in by defining Symbol.iterator.

Stuck? Three hints, smallest first
  1. 1. A generator that yields inside a for...of over its input is a lazy step: it does no work until something asks it for a value.
  2. 2. take is the only thing standing between you and a hung tab. It must stop pulling the moment it has enough, so count down and return.
  3. 3. Nothing runs until the consumer asks. Put a counter in a pass-through generator and you can see exactly how far up the chain each request travelled.

The answer

function* naturals() {
  let n = 1;
  while (true) yield n++;   // endless on purpose: only take() decides when to stop
}

function* metered(iterable, meter) {
  for (const value of iterable) {
    meter.count++;
    yield value;
  }
}

function* lazyMap(fn, iterable) {
  for (const value of iterable) yield fn(value);
}

function* lazyFilter(keep, iterable) {
  for (const value of iterable) if (keep(value)) yield value;
}

function* take(n, iterable) {
  if (n <= 0) return;
  let left = n;
  for (const value of iterable) {
    yield value;
    if (--left === 0) return;   // stop PULLING, not just stop yielding
  }
}

const meter = { count: 0 };
const squaresOfThrees = take(4, lazyMap((n) => n * n, lazyFilter((n) => n % 3 === 0, metered(naturals(), meter))));
const firstFour = [...squaresOfThrees];
const pulled = meter.count;

const zeroMeter = { count: 0 };
const nothing = [...take(0, metered(naturals(), zeroMeter))];
const pulledForNothing = zeroMeter.count;

const oneShot = take(3, naturals());
const firstPass = [...oneShot];
const secondPass = [...oneShot];
const freshRun = [...take(3, naturals())];

const shortSource = [...take(10, ['GRP-1', 'GRP-2', 'GRP-3'])];
const eager = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12].filter((n) => n % 3 === 0).map((n) => n * n);

const stallRow = {
  from: 3,
  to: 6,
  *[Symbol.iterator]() {
    for (let i = this.from; i <= this.to; i++) yield i;
  },
};
const spread = [...stallRow];

console.log('first four :', firstFour, '| source values pulled:', pulled);
console.log('take(0)    :', nothing, '| pulled:', pulledForNothing);
console.log('one shot   :', firstPass, 'then', secondPass);
console.log('custom     :', spread);

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 answers come out of a source with no end', firstFour, [9, 36, 81, 144]);
test('and exactly twelve source values were pulled to produce them', pulled, 12);
test('the eager version over a guessed range agrees, having done all the work', eager, firstFour);
test('take(0) yields nothing and pulls nothing at all', [nothing, pulledForNothing], [[], 0]);
test('an iterator is single-use: the second pass is empty', [firstPass, secondPass], [[1, 2, 3], []]);
test('the generator function is reusable, though; calling it again starts over', freshRun, [1, 2, 3]);
test('take stops early when the source runs out first', shortSource, ['GRP-1', 'GRP-2', 'GRP-3']);
test('any object with Symbol.iterator can be spread', spread, [3, 4, 5, 6]);

Each of these generators is a pull, not a push. [...take(4, ...)] asks take for a value, which asks lazyMap, which asks lazyFilter, which asks the source. Nothing between them holds an array, so the chain works on a sequence with no end and the peak memory is one value per stage. The counter proves it: twelve numbers were pulled, because the fourth multiple of three is twelve, and the thirteenth was never asked for.

The eager assertion is the comparison worth staring at. [1..12].filter(...).map(...) gives the same answer, but only because someone guessed that twelve was far enough. Guess low and the answer is wrong; guess high and you build two throwaway arrays. Laziness removes the guess.

Two warnings. An iterator is consumed once — the second spread of oneShot is empty, which is why passing a generator to two functions leaves the second one with nothing, and why an iterable object with Symbol.iterator (fresh iterator per call) is the friendlier thing to hand around. And the loop guard in this runner rewrites while and for headers only, so a for...of over naturals() with no take around it hangs with nothing to stop it. Bound every endless sequence at the point of consumption.

Newsletter

New writing, when it lands.

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