The feature I will be discussing in this post is generators. This is a new feature that was introduced in ES6.
A generator is a function that can be stopped midway and start off from where it left. This is very different from a normal function which runs to completion and if started again will start from the beginning.
Let’s look at a normal function for generating Fibonacci numbers for n terms:
// program to generate fibonacci series up to n terms
// take input from the user
const number = parseInt(prompt("Enter the number of terms: "));
console.log("Fibonacci Series:");
for (i of fibonacci(number))
{
console.log(i);
}
function fibonacci(nums)
{
let fib = [0, 1];
let data = [];
for(let i = 2; i <= nums; i++)
{
fib[i]=fib[i - 1] + fib[i - 2];
data.push(fib[i]);
}
return data;
}
Code pen link – https://codepen.io/ragesh_d/pen/yLzNQPG
This is how you would create one using generators:
// Fibonacci generator
function* fibonacci()
{
[a, b] = [0, 1]
while (true)
{
yield a;
[a, b] = [b, a + b]
}
}
// Instantiates the fibonacci generator
var fib = fibonacci();
const number = parseInt(prompt('Enter the number of terms: '));
// gets first n numbers from the Fibonacci generator starting from 0
for (let i = 0; i < number; i++)
{
console.log(fib.next().value);
}
Code pen link – https://codepen.io/ragesh_d/pen/dyVoQdp
The advantage of the generator method is that the calling program does not get back a list but just the next value, this means that it does not need to store the whole list so space wise it’s a much more efficient approach.
Now let’s see the syntax to creating a generator function, as can be seen from the example the function* is used to differentiate a generator from a normal function. It also uses a yield which is like a return but the function will halt after returning until the calling function invokes it using a next().
Let’s go over some advantages of generators:
- Generator values are lazily evaluated and until a value is request it does not get computed
- Using generator can let you do much more memory efficient operations
Some disadvantages of generators are:
1. Once a generator has looped over a possible set of values it can’t restart , that’s why it’s usually to keep generators in a infinite loop.
2. It’s not easily possible to go back in value with a generator
- 1. Once a generator has looped over a possible set of values it can’t restart , that’s why it’s usually to keep generators in a infinite loop.
- 2. It’s not easily possible to go back in value with a generator
References:
https://github.com/lukehoban/es6features#promises
https://codeburst.io/understanding-generators-in-es6-javascript-with-examples-6728834016d5
By Ragesh
