Skip to content

Instantly share code, notes, and snippets.

@arekgotfryd
Created September 6, 2017 09:38
Show Gist options
  • Save arekgotfryd/8e4a40e049353ddc3197cb2388f84ab2 to your computer and use it in GitHub Desktop.
Save arekgotfryd/8e4a40e049353ddc3197cb2388f84ab2 to your computer and use it in GitHub Desktop.
Great Generator example ES6
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 }
// The yield (x + 1) is what sends out value 6.
// The second next(12) call sends 12 to that waiting yield (x + 1) expression, so y is set to 12 * 2, value 24.
// Then the subsequent yield (y / 3) (yield (24 / 3)) is what sends out the value 8.
// The third next(13) call sends 13 to that waiting yield (y / 3) expression, making z set to 13.
// Finally, return (x + y + z) is return (5 + 24 + 13), or 42 being returned out as the last value.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment