The generator concept exists in most languages, and is a very useful abstraction. Definitely learn and use it. Here’s what it looks like in Javascript:
function *aGeneratorFunction() {
console.log('stage 1');
yield 123;
console.log('stage 2');
yield "almost there";
console.log('stage 3, done');
return {foo: "bar"};
}
Make a “Generator” object and run it:
let gen = aGeneratorFunction();
gen.next(); // {value: 123, done: false}
> stage 1
gen.next(); // {value: "almost there", done: false}
> stage 2
gen.next(); // {value: {foo: "bar"}, done: true}
> stage 3, done
Generally speaking, you should yield the same type every time. I only used different types to get the idea across.
Example of how generators can be useful: they are evaluated lazily - i.e. only
as the consumer asks for the next value (.next()
). This implies O(1) memory
usage for generating series of any length (even infinite). More depth on the
Wikipedia page
.