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
yieldpauses and hands a value to the caller.- The argument to
nextbecomes the value of thatyield. returnandthrowon the generator drive it from outside.
Keywords and builtins used here
constfunctionifletreturnwhileyield
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.
Step 2 of 2 in Generators, step 11 of 16 in Functions & patterns.