Composing generators in JavaScript

It’s really nice, how one can compose generator functions in JavaScript using yield* to delegate from one generator to another.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
function* parents() {
  yield "Sonja";
  yield "Florian";
}
 
function* children() {
  yield "Linda";
  yield "Mathea";
}
 
function* family() {
  yield* parents();
  yield* children();
   
  // And not to forget...
  yield "Grampa";
}
 
for(var name of family()) {
  console.log(name);
}

Output:

Sonja
Florian
Linda
Mathea
Grampa