Skip to content

Instantly share code, notes, and snippets.

@DmitrySoshnikov
Last active April 7, 2018 12:31
Show Gist options
  • Save DmitrySoshnikov/6bfe14594a70444db737 to your computer and use it in GitHub Desktop.
Save DmitrySoshnikov/6bfe14594a70444db737 to your computer and use it in GitHub Desktop.
ES6 delegating generator
/**
* ES6 delegating generators.
*
* ES6 dramatically simplified calling of nested generators
* using "yield *" construct, which is called delegating
* generator.
*
* From history:
* Previously (in the original SpiderMonkey/Python) implementation
* we had to maintain a manual stack for it. The technique was
* called "trampolining", and basically emulated the call stack:
* a call to a nested generator had to suspend our execution saving
* on the stack, run the nested gen, and then restore (pop stack frame).
* The details of implementation can be found in this diff from 2011:
* https://gist.github.com/DmitrySoshnikov/1130172
*
* And ES6 did it much, much simpler :) No stacks, no "trampolines",
* just do the "yield *".
*
* by Dmitry Soshnikov <[email protected]>
* MIT Style License
*/
function* genScores() {
yield '-- Score 1';
yield '-- Score 2';
}
function* genData() {
yield 'John Doe';
yield 'Scores:';
yield* genScores();
yield 'Completed.';
}
for (var info of genData()) {
console.log(info);
}
// Output:
// John Doe
// Scores:
// -- Score 1
// -- Score 2
// Completed.
@demisx
Copy link

demisx commented Dec 11, 2014

👍 Nice.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment