Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

187
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda