Good evening. I understand the generators in ES6 and decided, for example, to write a small example of a "recursive" generator
function* f(val) { yield val; yield* f(val - 1); } const it = f(3); console.log(it.next().value); console.log(it.next().value); console.log(it.next().value); console.log(it.next().value);
The console output surprised me a bit
2 0 -2 -4
As I understand it, the generator works according to the principle "reached the yield out of the generator with the object". That is, it turns out:
- The first line is
console.log(it.next().value)
Here we wake up the generator and stop at theyield val
and exit the generator that will sleep before the next call. In this case,val
will be equal to 3 and in the console it should output 3, respectively. Here I was originally wrong. - In the second line of
console.log(it.next().value)
it seemed to me that we gave the generator control to ourselves, where the value ofval
should have become 2 and again reach the lineyield val
, and in the console should output the number 2. Etc. in the following paragraphs.
Help please understand where I was wrong?