Search code examples
javascriptmemoization

Not able to clear Javascript Memoized function cache


I am trying to clear the memoized cache object but tried different solutions like prototype, call and bind but not able to make it work. Any help would be appreciated.

function memoize(func) {
  let cache = {};
  return function() {
    function clear() { cache = {}; }
    const key = JSON.stringify(arguments);
    if(cache[key]) { return cache[key]; }
    const result = func.apply(this, arguments);
    cache[key] = result;
    return result;
  }
}

function square(num) {
  console.log('calling square of', num);
  return num*num;
}

const memoizedSquare = memoize(square);

memoizedSquare(1);
memoizedSquare(1);
memoizedSquare(2);
memoizedSquare.clear(); // getting error on this line
memoizedSquare(2);
memoizedSquare(3);

function addition(a,b,c,d) {
  console.log('calling addition of', a,b,c,d);
  return a+b+c+d;
}

const memoizedAddition = memoize(addition);

memoizedAddition(1,2,3,4);
memoizedAddition(1,2,3,4);
memoizedAddition(4,2,3,1);
memoizedAddition(6,7,8,9);
memoizedAddition(6,7,8,9);


Solution

  • For your memoizedSquare.clear() to work, the function that you return from memoize() should have a clear property added to it. At the moment, your code declares the clear() function inside of the returned function, but isn't accessible to your calling code as it isn't exposed in any way. Since functions are objects in JavaScript, you can add a property to it just like you would with an ordinary object with dot notation, for example:

    function memoize(func) {
      let cache = {};
      function fn() {
        const key = JSON.stringify(arguments);
        if(cache[key]) { return cache[key]; }
        const result = func.apply(this, arguments);
        cache[key] = result;
        return result;
      }
      
      fn.clear = function() { cache = {}; }
      return fn;
    }
    
    function square(num) {
      console.log('calling square of', num);
      return num*num;
    }
    
    const memoizedSquare = memoize(square);
    
    console.log(memoizedSquare(1));
    console.log(memoizedSquare(1));
    console.log(memoizedSquare(2));
    memoizedSquare.clear(); // getting error on this line
    console.log(memoizedSquare(2));
    console.log(memoizedSquare(3));