Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

186
Views
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

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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));
about 4 years ago · Juan Pablo Isaza Report

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!