Search code examples
javascriptfunctionloopsfibonacciiife

IIFE Fibonacci function without value


guys. Hope everything is well with you.

I need to make an IIFE function, which can be declared without entering of any values:

const fibonacciConst = function fibonacciFunction() {
        // using helper function;
}

fibonacciConst(); // 1 in console.log
fibonacciConst(); // 1 in console.log
fibonacciConst(); // 2 in console.log
fibonacciConst(); // 3 in console.log
fibonacciConst(); // 5 in console.log

Mine code is working only with value in IIFE, that's the problem:

function fibonacciFunction() { 
    (function helperFibonacci(n) {
    let a = 0, b = 1, c = n;
    for(let i = 2; i <= n; i++) {
        c = a + b;
        a = b;
        b = c;
    }
    console.log(c);
    return c;
})(8); // without value here will be 'undefined'
}

const fibonacciConst = fibonacciFunction();

fibonacciConst; // 21 in console.log

I understood that in this task we need 2 functions: 1 function will be declaring another IIFE function inside, which is calculating result. The solution is preferably as simple as possible. Unfortunately, most solutions in google require you to enter a value, or difficult way with array, arrow functions etc. :(


Solution

  • You need to keep the state around somehow. One option would be a closure:

    function makeFibonacci() {
        let a = 0, b = 1
    
        function inner() {
            [a, b] = [b, a + b]
            return a
        }
    
        return inner
    }
    
    let fib = makeFibonacci()
    
    console.log(fib(), fib(), fib(), fib(), fib(), fib(), fib(), fib(), fib(), fib(), fib(), fib(), )