-2
var yourself = {
    fibonacci : function(n) {
        return n === 0 ? 0 : n === 1 ? 1 : 
        this.fibonacci(n -1) + this.fibonacci (n-2)
    }
};

This function is constantly setting the value of its 'fibonacci' property based on the arguement supplied for 'n' parameter of the function. I would like to refactor the function to reduce execution time

Stephen Ostermiller
  • 23,933
  • 14
  • 88
  • 109

2 Answers2

1

Using dynamic programming, Memoization that cache the already calculated result

read more about memoization here

const memoFib = function () {
    let memo = {}
    return function fib(n) {
        if (n in memo) { return memo[n] }
        else {
            if (n <= 1) { memo[n] = n }
            else { memo[n] = fib(n - 1) + fib(n - 2) }
            return memo[n]
        }
    }
}

const fib = memoFib()
console.log(fib(50));
Obaida Alhassan
  • 516
  • 1
  • 5
  • 12
0

You could implement some kind of caching. This way you don't need to recalculate the same result multiple times.

var yourself = {
    fibonacci : function(n, cache = new Map()) {
        if(cache.has(n)) return cache.get(n);
        if(n === 0) return 0;
        if(n === 1) return 1;
        
        const start = this.fibonacci(n-1, cache);
        const end = this.fibonacci(n-2, cache);
        
        cache.set(n-1, start);
        cache.set(n-2, end);
        
        return start + end;
    }
};

console.log(yourself.fibonacci(40));
Reyno
  • 6,119
  • 18
  • 27