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?