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

145
Vistas
javascript automatic memoization of function

I'm trying to implement memoization in javascript. here's the code:

function memoize(func) {
    var history = {}

    var inner = function(n) {
        if (n in history) {
            return history[n];
        }
        let result = func(n)
        history[n] = result;
        return result;
    }
    return inner;
}

function fib(n) {
    if (n <= 1) {
        return n;
    }
    return fib(n-1) + fib(n-2)
}
/*
fib = memoize(fib);
console.log(fib(20)) // O(n)
*/
/*
fib2 = memoize(fib);
console.log(fib2(20)) // O(2^n)
*/

it works.. I can calculated values in O(n) but I lost the original function. any way to still have the original fib function accessible? thanks

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

If you want to retain the original un-memoized version of fib you'll need to modify fib in some way, such as passing your recursive function as an argument. Otherwise, the recursive fib calls will remain as the un-memoized versions of your function.

eg:

function memoize(func) { // potentially update this to accept as hash function to calculate the key for `history` to make this more generic
  var history = {}
  var inner = function(n, ...args) {
    if (n in history) {
      return history[n];
    }
    let result = func(n, ...args);
    history[n] = result;
    return result;
  }
  return inner;
}

function fib(n, recursiveFn = fib) {
  if (n <= 1) {
    return n;
  }
  return recursiveFn(n - 1, recursiveFn) + recursiveFn(n - 2, recursiveFn)
}

const fastFib = memoize(fib);
console.log(fastFib(40, fastFib)); // O(n)
const slowFib = fib(40); // O(2^n)
console.log(slowFib);

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