Memoize Function in JavaScript. Is this the correct way of writing memoize function in JavaScript? Please provide correct one if it is wrong.
My Code:
let cache = {}
function sum(a,b)
{
console.log(`Entering sum function ${a} & ${b}`)
return a+b;
}
function memo(a,b)
{
let key = a+""+b
// console.log(cache[key])
if(cache[key])
{
// console.log(cache[key])
return cache[key]
}
else
{
cache[key] = sum(a,b)
return cache[key]
}
// console.log(cache)
}
console.log(memo(1,2))
console.log(memo(3,2))
console.log(memo(3,2))
console.log(memo(1,2))
console.log(memo(5,2))
As pointed out in comments, your key generation is error-prone. As long as you stick to primitive values, you can just use json:
Now,
if(cache[key])is no good either, because0could be a valid result. Better would beif (key in cache)That said, your memoizer only works with one particular function, but a "real" one should be a HOF, that is, accept an arbitrary function and return another function that wraps it:
Try to code this memoizer, come back to us if you have questions.