Generators emulate the behavior of a closure where they wrap an initial value then can take subsequent values through next
to yield something based on that initial wrapped value. This lesson walks through creating a closure then re-creating the same behavior with a generator.
John Lindquist: [0:00] A standard closure in JavaScript looks something like this, we'll call a makeAdder, and this can be the x value, and then we can return a function that takes a y value, then return x + y. You essentially capture this x value inside of this function so that when we use our makeAdder, we'll call this add2 function, say makeAdder(2).
[0:27] That 2 gets passed into here and then gives us back a function called add2 which we've named this function add2, and any time I use add2 to like 1, it will log out 3, because this add2 function has a 2 right here, and then we're passing in 1 right there, so that's just 2 + 1 and we now have an add2 function which we can reuse. We can make an add3 function, and add4 function, and as many different adding functions that we want just by passing in a different value there.
[0:58] Now we can take a really similar approach with generators, I'll call this makeAdderGenerator, and we need our * here. The syntax here would be passing in the x here, and then yielding our initial state because in our first iteration we can't pass a value in. Then for the second iteration, we can say let y = yield x, and then yield x + y.
[1:25] We'll call this a let add2Iterator makeAdderGenerator with a 2, and we'll do add2Iterator, this is our initial state so we can log that out, and that should just be 2, so 2 and done false. Then if we call next again and pass a 1 into here, hit save, you'll see we now have a 2 and a 3. The initial state being 2, and the next state being a 3.
[1:52] Now if we try to do this again, because there's no more yield statements, it would say undefined and done true, because there's no yields after this. What you can do is wrap this yield in a while true which is essentially an infinite loop, but because the execution of this gets paused every single time, it's safe to use an infinite loop because it will get to yield and then pause, yield and then pause, each time we call next.
[2:19] Our problem right now is if we pass in 2 here, we still get 3 because we're only setting y on the second iteration here, remember this is the end of the first iteration, and this is the beginning of the second iteration. The last thing to do is just to assign y to the result of yield x + y. Go ahead and save, and now we have 4.
[2:42] I'm just going to move this down for clarity, that can look a little confusing on a single line. Now you can see the concept of an initial state, and then yielding new states every time this gets updated.