javascript

How do i define the fib() function, which returns the next Fibonacci number after each call?


Define the fib() function, which returns the next Fibonacci number after each call. The solution should inject only the name of the fib function into the global scope and not create additional properties of the fib function or its properties.

I need the help by using JavaScript, I'm troubling with the solution..

I've tried something like this:

    let a = 0, b = 1;
    return function() {
        let next = a;
        a = b;
        b = next + b;
        return next;
    };
}

const getNextFib = fib();

and this:

function fib() {
    let a = 1, b = 1;
    return () => {
        let result = a;
        a = b;
        b = result + b;
        return result;
    };
}

but none is legit. (it's like a test for programming lectures)


Solution

  • Another possible solution is to use generator function which will yield values on demand. So it'll look something like this

        function* generateFibonacci(){
        let prev = 0, curr = 1, res
    
        while(true){
            res = prev + curr
            yield res
            prev = curr
            curr = res
        }}
        
        const fibonacci = generateFibonacci()
        
        fibonacci.next().value // output - 1
        fibonacci.next().value // output - 2
        fibonacci.next().value // output - 3
        fibonacci.next().value // output - 5
        // and so on...
    
    

    So everytime you call the next method you'll get the next yielded value.

    Read more about generators