Search code examples
javascriptlodashmemoization

How is the entire memoize cache deleted in lodash?


When using _.memoize from lodash, is it possible to delete the entire cache?

I have seen a few discussions on github: https://github.com/lodash/lodash/issues/1269 https://github.com/lodash/lodash/issues/265

But I'm still not 100% clear on how this would be approached, if you wanted to do a page wide cache clear? Is the intention to set it to a WeakMap first, then call clear as required?


Solution

  • Lodash doesn't provide a way to delete cache of all memoized functions. You have to do it one by one. It's because every memoized function has its own cache object instance.

    Look at lodash memoize source code:

    function memoize(func, resolver) {
      var memoized = function() {
        // ...
      }
      memoized.cache = new (memoize.Cache || MapCache);
      return memoized;
    }
    

    The GitHub discussions you referred to are about clearing cache of a single memoized function.

    You can keep all memoized functions into an array so that it's able to iterate over them and clear cache one by one.

    const func1 = _.memoize(origFunc1);
    const func2 = _.memoize(origFunc2);
    
    const memoizedFunctions = [];
    memoizedFunctions.push(func1);
    memoizedFunctions.push(func2);   
    
    // clear cache of all memoized functions
    memoizedFunctions.forEach(f => f.cache = new _.memoize.Cache);