Generators in JavaScript
Let’s write a function that let’s us take an n-sized subset of some iterator.
Cycling
Imagine you have an array, and you want to cycle through all the values, ad infinitum.
Skipping
Now imagine you’re a teacher, and you are going to select a student for a task. However, each time you count, you skip a student.
Generators
The functions were using above are called generators. They’re special functions that pause execution and yield a value. When they are executed the next()
time, execution is resumed, as opposed to done over again, like a normal function. They are done when they finally return
.
**Generators** are functions with the ability to pause and resume execution. A generator looks like a function but behaves like an iterator.
This gives us another way to iterate. One of the key functionalities provided is the ability to work with infinite series. When you iterate using a collection, all the values are sitting in memory, so you don’t have that ability.
Halving
Achilles is running a race. Each step is half the length of his previous step. How many steps until he’s not moving at all?
Theoretically, half of any number, ad infinitum, will never reach 0. Only it’s limit does.
However, in a programming language like JS, we’re dealing with finite resources, and that number will at some point reach 0. Let’s find out when.
Finally, let’s take a look at some of the helper functions we’ve been using. It might be useful to reflect on JavaScript’s iterator protocol.
Sources
- Understanding JavaScript Generators, inspired
take
andnaturalNumbers
- MDN
Wow! You read the whole thing. People who make it this far sometimes
want to receive emails when I post something new.
I also have an RSS feed.