1

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))
gog
  • 10,367
  • 2
  • 24
  • 38
  • Nope, this is not how you implement memoization, you should be using the existing object values to calculate the next sum values of subsequent set. A best example is fibonacci, – Amaarockz Oct 10 '22 at 06:48
  • looks sort of OK to me, sure, it's not like fibonacci or factorial examples that are everywhere, but I would say this is a valid implementation – Jaromanda X Oct 10 '22 at 07:16
  • oh, one issue .... try `memo(12, 1)` followed by `memo(1, 21)` – Jaromanda X Oct 10 '22 at 07:20

1 Answers1

0

As pointed out in comments, your key generation is error-prone. As long as you stick to primitive values, you can just use json:

let key = JSON.stringify([a, b])

Now, if(cache[key]) is no good either, because 0 could be a valid result. Better would be if (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:

function sum() ...

function memoize(fn) ...

let memoSum = memoize(sum)

memoSum(40, 2)  // computed
memoSum(40, 2)  // cached

Try to code this memoizer, come back to us if you have questions.

gog
  • 10,367
  • 2
  • 24
  • 38