I am reading "The JavaScript Handbook" by Flavio Scopes. He introduces the concept of Generators.
function* calculator(input) {
var doubleThat = 2 * (yield(input / 2))
var another = yield(doubleThat)
return (input * doubleThat * another)
}
// He then runs the following code
const calc = calculator(10)
console.log(calc.next())
Output
{value: 5, done: false}
calc.next(7);
Output:
{value: 14, done: false}
I understand the first output, but I don't understand the second one. Why is the output 14?
My understanding is that the next time .next() is called on calc, it should continue on the line AFTER the one on which it last paused.
Well, that line is this one: var another = yield(doubleThat) and the value of the variable doubleThat at that point should be 10, so I'm expecting the second yield to return an object with a value of 10.
I don't think the example in the book is a good one, as I understand the concept of Generators (Python) and Iterators (C++/Python), and I understand other Javascript examples of Generators - but I simply do not understand what is going on here.
Can anyone explain why the value returned after calc.next(7) is 14?
p5, that Processing-like "art" library. The need for all sorts of coordinated iteration goes great with generators, because the "iteration" can be nicely hidden in generator functions that can be composed in all sorts of neat-o ways.