Sub topic 11
Delegating with yield*
This chapter assumes you can write generator functions with function* and yield. It also assumes you know that for...of and spread ignore a generator's return value. Here you will learn how one generator can hand control to another iterable, and what it gets back when that iterable finishes.
The problem yield* solves
Sometimes a generator needs to produce every value of another generator. Without delegation you write a loop yourself:
function* letters() {
yield 'a';
yield 'b';
}
function* withLoop() {
for (const x of letters()) {
yield x;
}
yield 'c';
}
console.log([...withLoop()]); // [ 'a', 'b', 'c' ]yield* replaces that loop with one expression. It takes any iterable, steps through it, and passes each value straight to whoever is consuming the outer generator.
How yield* works
function* inner() {
yield 'a';
yield 'b';
return 'inner done';
}
function* outer() {
const result = yield* inner();
yield result;
yield* [1, 2];
}
console.log([...outer()]); // [ 'a', 'b', 'inner done', 1, 2 ]This example shows three rules:
yield* inner()passes along'a'and'b'one at a time. The outer generator stays paused at theyield*untilinnerfinishes.- The
yield*expression evaluates to the delegated generator'sreturnvalue. That value arrives withdone: true, so a plain loop would drop it.yield*captures it. yield*accepts any iterable, not only generators. Arrays, strings, Maps, Sets, and your own iterables all work.
yield* also forwards calls to next(value), throw(), and return() to the inner iterator. The next chapter covers those methods.
Recursion with yield*
Delegation makes recursive structures easy to walk. Each call handles one node and delegates its children:
function* walk(node) {
yield node.value;
for (const child of node.children) {
yield* walk(child);
}
}
const tree = {
value: 1,
children: [
{ value: 2, children: [{ value: 3, children: [] }] },
{ value: 4, children: [] }
]
};
console.log([...walk(tree)]); // [ 1, 2, 3, 4 ]The consumer sees one flat sequence and never deals with the nesting.
Common error: forgetting the star
yield without the star produces the generator object as a single value. It does not produce that generator's contents:
function* inner() {
yield 'a';
yield 'b';
}
function* broken() {
yield inner();
}
console.log([...broken()]); // [ Object [Generator] {} ]Exercise
What does console.log([...g()]) print, given function sub() { yield 1; return 2; } and function g() { const r = yield sub(); yield r 10; yield* 'ok'; }?
Show answer
[ 1, 20, 'o', 'k' ]. The yield passes along 1, then evaluates to sub's return value 2, so g yields 20. The yield on the string 'ok' yields each character separately.
Exercise
Write a generator flatten(arr) that yields every non-array value from an arbitrarily nested array, so [...flatten([1, [2, [3]], 4])] gives [ 1, 2, 3, 4 ].
Show answer
function flatten(arr) { for (const x of arr) { if (Array.isArray(x)) yield flatten(x); else yield x; } }