Created
October 10, 2017 07:16
-
-
Save andrewglind/3c0d3b85a9ee78275b8e6dcf1bc2d629 to your computer and use it in GitHub Desktop.
2-way generator - My explanation of the example at https://davidwalsh.name/es6-generators
This file contains 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
/************************* | |
First call it.next(): has the effect of starting the function, there is no yield waiting for input at this point, | |
therefore yield (line 13) passes back the value 6, and is now waiting for input | |
Second call it.next(12): yield (line 13) is paused and waiting for input, input is 12, therefore y is assigned the value 24 (2 * 12). | |
yield (line 14) passes back 8 (24(y) / 3), and is now waiting for input | |
Final call it.next(13): yield (line 14) is paused and waiting for input, input is 13, therefore z is assigned the value 13. | |
function returns x + y + z (5 + 24 + 13) = 42 | |
*************************/ | |
function *foo(x) { | |
var y = 2 * (yield (x + 1)); | |
var z = yield (y / 3); | |
return (x + y + z); | |
} | |
var it = foo( 5 ); | |
// note: not sending anything into `next()` here | |
console.log( it.next() ); // { value:6, done:false } | |
console.log( it.next( 12 ) ); // { value:8, done:false } | |
console.log( it.next( 13 ) ); // { value:42, done:true } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment