Overview
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
Short Course
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]
Task
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].
Test Suites
Pending
Next
Output