JavaScript · Level 3 Iteration

Generators (function*)

Write a function* that hands out numbers one at a time with yield, so even an endless sequence costs nothing until you ask for the next value.

  • function* and yield
  • next() resumes the generator
  • Spreading a generator into an array

A function* pauses at each yield and resumes on the next request. Generators are lazy: nothing runs until you call next(), spread them or loop with for...of.

function* countdown(n) {
  while (n > 0) yield n--;
}

const it = countdown(3);
it.next();          // { value: 3, done: false }
[...countdown(3)];  // [3, 2, 1]

Write a generator range(start, end, step = 1) that yields start, start + step, … while the number is below end, e.g. [...range(1, 10, 3)] is [1, 4, 7].

solution.js
Test Suites Pending
Output