Generator Functions in Javascript

We will be building on what we discussed in previous post generator-functions-using-co

Here we will focus on how to implement something analogous to co. i.e. actually implement an iterable.

How to run the function*

Steps involved in running through a generator function. If its a bit confusing, it will be clear when we look at the implementation.

  1. we first invoke the function and store it in a variable.
  2. The invocation of the function returns an iterable object back to us.
  3. We can call ‘next‘ on this object to take us to the first yield point in the function.
  4. this call will give us back an object with the properties of value and done
  5. we can continue iterating through this until we are done or stop at any point

Example

So, with the basic understanding of a generator out of the way,  here is the same code implemented in previous post but using a function called iter that shows the implementation of the iterable

 

 

 




No Comments


You can leave the first : )



Leave a Reply

Your email address will not be published. Required fields are marked *