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?
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.
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.
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.
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.
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);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With