Last active
August 29, 2015 13:56
-
-
Save getify/8902610 to your computer and use it in GitHub Desktop.
how i wish JS generators could have worked
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
// I wish that generators allowed you to call next(..) | |
// at the first step with a value, and that value was | |
// the first (named) argument to the generator itself. | |
// | |
// see `next(3)` below setting `msg` to `3`. | |
// | |
// It would mirror how `return` is overloaded to do the final | |
// `yield`: by letting an argument be the initial "yield target" | |
// of an iterator-sent message. | |
function* gen(msg) { | |
console.log( msg ); // 3 | |
var x = yield (msg * 3); | |
console.log( x ); // 10 | |
var y = 2 * (yield (x * 4)); | |
console.log( y ); // 100 | |
return x * y; // 1000 | |
} | |
var it = gen(); | |
// send `3` as `msg` argument | |
it.next( 3 ); // {done:false, value:9} | |
it.next( 10 ); // {done: false, value:40} | |
it.next( 50 ); // {done: true, value:1000} |
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
// We could even combine, where initial messages | |
// to gen(..) call are just curried to actual | |
// generator invocation. | |
function* gen(msg1, msg2) { | |
console.log( msg1 ); // "foo", curried from the gen(..) call | |
console.log( msg2 ); // 3 | |
var x = yield (msg2 * 3); | |
console.log( x ); // 10 | |
var y = 2 * (yield (x * 4)); | |
console.log( y ); // 100 | |
return x * y; // 1000 | |
} | |
var it = gen( "foo" ); // curry "foo" as `msg1` argument | |
// now send `3` as `msg2` argument | |
it.next( 3 ); // {done:false, value:9} | |
it.next( 10 ); // {done: false, value:40} | |
it.next( 50 ); // {done: true, value:1000} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment