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))