Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 2

Take n items from an infinite generator in JavaScript

7 An infinite sequence, and taking from it

hard

Write an infinite generator of natural numbers and a take(iterable, n) that pulls only the first n. Count how many values the source actually produced. Then take twice from the same generator and explain the second result.

Stuck? Three hints, smallest first
  1. 1. An infinite generator is just while (true) yield .... Nothing runs until something pulls.
  2. 2. take should return as soon as it has enough, which is what stops the source.
  3. 3. Ending a for...of early closes the iterator it was reading. That is fine for a fresh generator and fatal for a shared one.

The answer

function* naturals(from = 1) {
  let n = from;
  while (true) yield n++;
}

function* take(iterable, count) {
  if (count <= 0) return;
  let taken = 0;
  for (const value of iterable) {
    yield value;
    if (++taken === count) return;
  }
}

// A version that drives next() itself, so it never closes the source.
function* takeFrom(iterator, count) {
  for (let i = 0; i < count; i++) {
    const step = iterator.next();
    if (step.done) return;
    yield step.value;
  }
}

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

const firstThree = [...take(counted(), 3)];
const producedForThree = produced;
const nothing = [...take(counted(), 0)];
const producedAfterZero = produced;

const shared = naturals();
const twiceOverForOf = [[...take(shared, 2)], [...take(shared, 2)]];
const openSource = naturals();
const twiceOverNext = [[...takeFrom(openSource, 2)], [...takeFrom(openSource, 2)]];

console.log('first three   :', firstThree, 'source produced', producedForThree);
console.log('take(..., 0)  :', nothing, 'source produced', producedAfterZero);
console.log('shared via for...of:', twiceOverForOf, '<- second pass is empty');
console.log('shared via next()  :', twiceOverNext);

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.

7 checks

test('take pulls only what it needs', firstThree, [1, 2, 3]);
test('and the source produced exactly three values', producedForThree, 3);
test('taking zero pulls nothing at all', [nothing, producedAfterZero], [[], 3]);
test('taking more than exists stops at the end', [...take([1, 2], 5)], [1, 2]);
test('an infinite source is fine as long as you stop', [...take(naturals(10), 3)], [10, 11, 12]);
test('for...of CLOSES the generator on early exit, so a shared source is spent', twiceOverForOf, [[1, 2], []]);
test('driving next() by hand leaves it open', twiceOverNext, [[1, 2], [3, 4]]);

The produced === 3 assertion is the point of lazy sequences. The source is written as though it goes on for ever, and the cost is set by the consumer, not the producer. Rewrite counted to build an array first and there is no n at which it terminates.

The sixth assertion is the trap, and it costs people an afternoon. for...of is specified to call return() on its iterator when it exits early — the same mechanism as exercise 3's cleanup — and on a generator that means "you are finished". So a take written with for...of quietly destroys any source it is handed twice. [[1, 2], []] is the assertion of that.

takeFrom is the fix: drive next() yourself and never enter a for...of, so nothing calls return(). That is why library helpers take an iterator when they intend to leave it resumable and an iterable when they intend to consume it whole. Naming the parameter honestly is most of the documentation.

Newsletter

New writing, when it lands.

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