We will see how to create an
iterator with generator function. Iterator contains a set of values in a sequence. We can go through the elements in an iterator with a
for loop. For this example, we will create an iterator for
Generator is just another function. The only difference is that it can be paused and resumed. While the normal functions use
return to give back a value and stop its execution, a generator function uses
yield to give a value back and pause the function. We can resume the function with the
next() command and the function will give back the value in the next yield. We can also go through the values in a generator with a loop. The generator functions can also have a
return statement which can be used to terminate its execution.
*. It could also have a yield statement.
In the Fibonacci series, the first two numbers are 0 and 1 and the rest is the sum of previous two values. So, it goes like
0, 1, 1, 2, 3, 5, 8, 13, 21, .... The code for getting Fibonacci Numbers less than 100 is this.
Note that ES6 is required for running this code. We first define the generator function
getFibonacci() with the
*. The first value in the sequence is
0, so we have to return that with an yield. We can use an expression with yield statement and the result of the expression is send out with yield. Now we store the previous two values in
b. The starting values of
1 respectively, the first two values in the sequence. We can assign value to
a and yield it in a single statement.
We start an infinite
while loop. We now yield the value in
b, which is now the second number in the sequence. Now we set
b to the sum of
b and set
a as the previous value of
b. This can be done simply by,
b will contain the third number in the sequence, which is then given out with yield. This goes on and on with
b always having the next number in the sequence.
This generator acts as an iterator factory for Fibonacci Numbers. We can loop through this iterator with the
for .. of loop. As this gives all the Fibonacci Numbers till infinity, we need a
break condition. Here, we take the Fibonacci Numbers less than 100 and logs it.
The python implementation of this same problem is very similar. The code for the solution is this.
We start with the
getFibonacci() generator function. In python, there is no difference between generators and normal function definition. The only difference is in the appearence of the
0 and then assign the initial values to
As before, we than have an infinite loop which yields the next value in the sequence and calculates new values of
To loop through the numbers in the
getFibonacci() iterator, we can use