skip to Main Content

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)

3

Answers


  1. The best solution for your problem is closures.which helps to return the function from the function and the inner function stores the value of the variables of outer function without regards of function call.

    This fibonacci function is written using closure to generate the Fibonacci series by just calling the function without storing the variables curr , prev in global scope.

    
    function fibonacci() {
        let prev = 1, curr = 1;
    
        return function () {
            const next = prev + curr;
            [prev, curr] = [curr, next];
            return prev;
        };
    }
    
    
    let next_fibonacci = fibonacci();
    
    for(let i=1; i <= 5;i++){
       console.log(next_fibonacci());
    }
    
    

    If you don’t know about closures then go and refer closures

    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
  3. Only one thing in global scope (fib).

    No additional functions wrapping fib, the setup is handled by iife.

    (function () {
      let a = 1, b = 1;
      fib = () => {
        let result = a;
        a = b;
        b = result + b;
        return result;
      };
    })();
    
    console.log(fib());
    console.log(fib());
    console.log(fib());
    console.log(fib());
    console.log(fib());
    console.log(fib());
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search