Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 857
Chris Avatar asked Jul 05 '16 23:07

Chris


People also ask

How does Lodash memoize work?

Syntax. Creates a function that memoizes the result of func. If resolver is provided, it determines the cache key for storing the result based on the arguments provided to the memoized function. By default, the first argument provided to the memoized function is used as the map cache key.

Is memoization a cache?

Memoization is actually a specific type of caching that involves caching the return value of a function based on input. Caching is a more general term. For example, HTTP caching is caching but it is not memoization.

How does Javascript memoize work?

In programming, memoization is an optimization technique that makes applications more efficient and hence faster. It does this by storing computation results in cache, and retrieving that same information from the cache the next time it's needed instead of computing it again.

What is a Memoized value?

In computing, memoization or memoisation is an optimization technique used primarily to speed up computer programs by storing the results of expensive function calls and returning the cached result when the same inputs occur again.


2 Answers

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);
like image 200
aleung Avatar answered Sep 28 '22 15:09

aleung


update answer in 2019 :), lodash has added clear function to cache method so the way to clear cache can be

memoizedFunctions.forEach(f => f.cache.clear());

tested lodash version 4.17.13

like image 45
duc mai Avatar answered Sep 28 '22 17:09

duc mai