Search code examples
javascriptdynamic-programmingfibonaccimemoization

How can i reduce the time of execution of this code


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


Solution

  • 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));