Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 1

Infinite generator with take() in JavaScript

55 A generator that never ends, and taking five

fair

Write a generator that counts for ever, then write take(iterable, n) and takeWhile(iterable, ok) as generators so you can get a finite answer out of it. Prove the source only produced as many values as were asked for.

Stuck? Three hints, smallest first
  1. 1. while (true) yield n++; is fine, because nothing runs until it is pulled.
  2. 2. take loops the source with for...of and returns once it has enough.
  3. 3. Count the source’s work in a variable outside it, and the laziness becomes something you can assert.

The answer

function* naturals(from = 1) {
  let n = from;
  while (true) yield n++;                     // never ends, and never runs unpulled
}

function* take(iterable, count) {
  if (count <= 0) return;
  let left = count;
  for (const item of iterable) {
    yield item;
    if (--left === 0) return;                 // stops pulling the source
  }
}

function* takeWhile(iterable, ok) {
  for (const item of iterable) {
    if (!ok(item)) return;
    yield item;
  }
}

function* mapped(iterable, fn) {
  for (const item of iterable) yield fn(item);
}

function* fib() {
  let [a, b] = [0, 1];
  while (true) {
    yield a;
    [a, b] = [b, a + b];
  }
}

let produced = 0;
function* counted() {
  let n = 1;
  while (true) {
    produced++;
    yield n++;
  }
}

const firstFive = [...take(naturals(), 5)];
const firstThree = [...take(counted(), 3)];
const nothing = [...take(naturals(), 0)];
const fares = [...take(mapped(naturals(), (n) => n * 25000), 3)];
const firstEight = [...take(fib(), 8)];
const underHundred = [...takeWhile(fib(), (n) => n < 100)];
const bothProtocols = [typeof naturals().next, typeof naturals()[Symbol.iterator]];

console.log('take 5    :', firstFive);
console.log('laziness  :', firstThree, 'and the source ran', produced, 'times');
console.log('take 0    :', nothing, '| mapped then taken:', fares);
console.log('fib 8     :', firstEight);
console.log('under 100 :', underHundred);

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('five values out of an endless source', firstFive, [1, 2, 3, 4, 5]);
test('and the source produced exactly three when three were asked for', [firstThree, produced], [[1, 2, 3], 3]);
test('taking none pulls nothing at all', nothing, []);
test('generators compose, and the composition stays lazy', fares, [25000, 50000, 75000]);
test('the same shape gives fibonacci', firstEight, [0, 1, 1, 2, 3, 5, 8, 13]);
test('takeWhile stops at the first value that fails the test', underHundred.length, 12);
test('so the last one through is the largest under a hundred', underHundred[underHundred.length - 1], 89);
test('a generator object is an iterator and an iterable at the same time', bothProtocols, ['function', 'function']);

An endless generator is safe because it is a description, not a computation: naturals() holds a plan and a cursor, and while (true) only advances when someone pulls. The second assertion is the one that proves it — three values requested, three iterations run, no fourth. Chain mapped in front and nothing changes: no intermediate array is ever built, unlike arr.map(...).slice(0, 3), which maps everything first.

The danger is on you. [...naturals()], Array.from(naturals()) or a for...of with no break will run until the tab dies; the loop guard on this page rewrites while and for headers, but a for...of has no condition to rewrite, so that is the one shape it cannot save you from. Always put a take, a takeWhile or a break between an endless source and a consumer that wants everything.

Newsletter

New writing, when it lands.

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