当使用 lodash
中的 _.memoize
时,是否可以删除整个缓存?
我在github上看到了一些讨论: https://github.com/lodash/lodash/issues/1269 https://github.com/lodash/lodash/issues/265
但我仍然不是 100% 清楚如何处理,如果您想清除页面范围的缓存?是否打算先将其设置为 WeakMap,然后根据需要调用 clear?
最佳答案
Lodash 不提供删除所有内存函数缓存的方法。你必须一项一项地做。这是因为每个内存函数都有自己的缓存对象实例。
看lodash memoize
source code :
function memoize(func, resolver) {
var memoized = function() {
// ...
}
memoized.cache = new (memoize.Cache || MapCache);
return memoized;
}
您提到的 GitHub 讨论是关于清除单个内存函数的缓存。
您可以将所有内存函数保存到一个数组中,以便它能够迭代它们并一个一个地清除缓存。
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);
关于javascript - lodash 中如何删除整个 memoize 缓存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38214551/