×

javascript · level 3 · unit 6 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

Generators are , so they can describe endless sequences.

An array must hold every value at once. A generator is lazy: it works out each value only when asked. So a generator can safely contain a loop that never ends, because it pauses at every yield.

The trick is to take only what you need. take stops after count values, and squares changes each value as it passes. Stack helpers like these into a , and each value flows through every step before the next one is even made.

function* naturals() {
  let n = 0;
  while (true) { n++; yield n; }
}
function* squares(items) { for (const n of items) { yield n * n; } }
function* take(items, count) {
  for (const item of items) {
    if (count === 0) { return; }
    count--;
    yield item;
  }
}
console.log([...take(squares(naturals()), 5)]);

Never spread an endless generator on its own: with no take in front, it would never stop.