Skip to content

Instantly share code, notes, and snippets.

@Kishanjvaghela
Created December 21, 2018 03:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Kishanjvaghela/250811d8a02a46de06707a6084614d2c to your computer and use it in GitHub Desktop.
Save Kishanjvaghela/250811d8a02a46de06707a6084614d2c to your computer and use it in GitHub Desktop.
Generator
function *foo(x) {
console.log('x is ' + x);
const y = yield (x + 1);
console.log('y is ' + y);
var z = yield (y + 2);
console.log('z is '+ z);
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 }
const a = it.next().value;
console.log('1st result '+ a);
const b = it.next(a*2).value;
console.log('2nd result '+ b);
const c = it.next(b/2).value;
console.log('3rd result ' + c);
// outbut
// "x is 5"
// "1st result 6"
// "y is 12"
// "2nd result 14"
// "z is 7"
// "3rd result 24"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment