Is this the correct way of writing memoise function in JavaScript?

37 Views Asked by At

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

There are 1 best solutions below

0
gog On

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.