fib

Iterators And Generators in JavaScript – How To Generate Fibonacci Sequence?

Iterators and generators are used in JavaScript to process a collection of data incrementally. Iterator is a function which will traverse through an array and return its current value and done state through another function called next(). 

function createIterator( array ){
    
    let currentIndex = 0;
    
    return {
        next(){
           return currentIndex < array.length 
               ? { value: array[ currentIndex++ ], done: false } 
               : { done: true } 
        }
    };
    
}

const testArray =  ['hello', 'world']
const iterator = createIterator(testArray)

console.log(iterator.next())
console.log(iterator.next())
console.log(iterator.next())

We can call the next() method as long as we can but once done will be true it will always show the done state true onward. Before that it will show the current value with the done state as false. 

Generator on the other hand generates a collection with the values we want. Here we are creating a function name *gen() and in there we are initialising a variable i with value 1. Then we will create an infinite while loop and in that while we will yield 1 and then we will multiply i with 2 and save it in i itself.

function *gen(){
    let i = 1
    
    while(true){
        yield i;
        i *= 2
    }
}

const generator = gen()

console.log(generator.next())
console.log(generator.next())
console.log(generator.next())

This generator will keep returning numbers by multiplying with 2 every time we will call next() method on generator and also it will return the done state as false. 

Now let’s generate a Fibonacci sequence using a JS generator.

function *fibonacci(){
    let a = 0;
    let b = 1;
    
    while(true){
        let current = a;
        a=b;
        b= current + a;
        yield current;
    }
}

const fib = fibonacci();

console.log(fib.next());
console.log(fib.next());
console.log(fib.next());
console.log(fib.next());
console.log(fib.next());
console.log(fib.next());
console.log(fib.next());
console.log(fib.next());