Search⌘ K
AI Features

Combining Generators

Explore how to combine multiple JavaScript generators using the yield* operator. Understand how to delegate iteration to other generators or iterable objects, enabling you to produce complex sequences like card suits and pips with concise and reusable code.

In the CardDeck class given in the below code widget, we have two generators:

  1. One to create the suits
  2. The other for pips

It would be a shame if we have to duplicate the code to create a series that contains both suits and pips. Thankfully, we don’t have to endure such pain—JavaScript provides a way to combine generators.

Delegating to already created generator

Let’s create a method, suitsAndPips(), in the CardDeck class.

Javascript (babel-node)
'use strict';
class CardDeck {
constructor() {
this.suitShapes = ['Clubs', 'Diamonds', 'Hearts', 'Spaces'];
}
//START:METHOD
*suits() {
for(const color of this.suitShapes) {
yield color;
}
}
//END:METHOD
//START:PIPS
*pips() {
yield 'Ace';
yield 'King';
yield 'Queen';
yield 'Jack';
for(let i = 10; i > 1; i--) {
yield i.toString();
}
}
//END:PIPS
//START:SUITSANDPIPS
*suitsAndPips() {
yield* this.suits();
yield* this.pips();
}
//END:SUITSANDPIPS
}
//START:USE
const deck = new CardDeck();
//END:USE
//START:USESUITSANDPIPS
for(const value of deck.suitsAndPips()) {
process.stdout.write(value + ' ');
}
//END:USESUITSANDPIPS
console.log();

In the suitsAndPips() ...