Search⌘ K
AI Features

Removing Noise With Generators

Explore how to create and use JavaScript generators to yield multiple values efficiently. Understand converting iterators to generators, calling generator functions, and handling multiple generators for complex sequences.

A generator, as the name indicates, generates values.

📍 For a function to serve as a generator, its name should lead with a * and its body should have one or more yield calls.

Creating a generator

Let’s convert the iterator method to a simple generator.

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
}
  • We replaced the ...