I was reading this article about javascript generators, and I reached the following snippet:
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 }
I don't understand the purpose of the first it.next()
. After executing it, this line, shouldn't the iterator be paused at var z = yield (y / 3)
, with y having the value of 6? Shouldn't it.next(12)
supply the param for yield (y / 3)
, and z be 4 after this? I don't understand why the result of the function is not 5 + 12 + 4. It's somehow as if the first it.next()
is ignored. Is this the case? Can someone please shed some light?