typestar

Generators, further in JavaScript

Two-way communication: yield sends out, next sends in.

function* accumulator(start = 0) {
  let total = start;
  while (true) {
    const received = yield total;
    if (received === undefined) return total;
    total += received;
  }
}

const running = accumulator();
console.log(running.next().value);
console.log(running.next(10).value);
console.log(running.next(5).value);
console.log(running.next().done);

function* inner() { yield 1; yield 2; }
function* outer() { yield 0; yield* inner(); yield 3; }
console.log([...outer()]);

How it works

  1. yield pauses and hands a value to the caller.
  2. The argument to next becomes the value of that yield.
  3. return and throw on the generator drive it from outside.

Keywords and builtins used here

The run, in numbers

Lines
18
Characters to type
461
Tokens
145
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 83 seconds.

Type this snippet

Step 2 of 2 in Generators, step 11 of 16 in Functions & patterns.

← Previous Next →