Last active
April 7, 2018 12:31
-
-
Save DmitrySoshnikov/6bfe14594a70444db737 to your computer and use it in GitHub Desktop.
ES6 delegating generator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
👍 Nice.