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.

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

Leave a Reply

Your email address will not be published. Required fields are marked *