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

133
Vistas
Memoize with inputs that have commutative property?

Imagine I have a function that simply sum up a list of numbers.


function add(...input) {
    return input.reduce((sum, num) => sum + num, 0)
}

I want to memorize this function to avoid unnecessary computation so I wrote a higher order function memoize

function memoize(fn, resolver) {
    const cache = new Map()
    
    return function(...args) {
        let key
        if(!resolver) key = args.join('')
        else key = resolver(...args)
        
        if (cache.has(key)) return cache.get(key)
        const val = fn(...args)
        cache.set(key, val)

        return val
    }
}

now if we give add the same list of numbers, it will try to get the sum from the cache first before it computes the sum.

However, the problem is that, the addition has associative property. E.g. add(1,2,3) and add(2,1,3) return the same value but the current implementation would treat them as different inputs so we have a cache miss but in reality it should be a cache hit.

Was wondering if there is any ways we can implement a cache that takes this associative property into account?

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