【问题标题】:How is the entire memoize cache deleted in lodash?lodash中如何删除整个memoize缓存?
【发布时间】:2016-11-07 22:43:38
【问题描述】:

当使用lodash中的_.memoize时,是否可以删除整个缓存?

我在github上看到过一些讨论: https://github.com/lodash/lodash/issues/1269 https://github.com/lodash/lodash/issues/265

但是,如果您想清除页面范围的缓存,我仍然不是 100% 清楚如何解决这个问题?是否打算先将其设置为 WeakMap,然后根据需要调用 clear?

【问题讨论】:

  • 再次调用memoize并覆盖你的记忆函数,缓存就消失了。
  • 我想删除所有/整个记忆的缓存函数

标签: javascript lodash memoization


【解决方案1】:

Lodash 没有提供删除所有记忆函数缓存的方法。你必须一件一件地去做。这是因为每个 memoized 函数都有自己的缓存对象实例。

看看lodashmemoizesource 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);

【讨论】:

  • 这对我来说非常有效,但在 Typescript 中我必须这样做:f.cache = new (_.memoize.Cache as any) 因为编译器拒绝执行 new 否则。我的 lodash 打字版本可能有问题。
  • 确实应该是new _.memoize.Cache
【解决方案2】:

2019 年更新答案 :),lodash 在缓存方法中添加了清除功能,因此清除缓存的方式可以是

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

经过测试的 lodash 版本 4.17.13

【讨论】:

    【解决方案3】:
    function _printName(name) {
      console.log(name);
    }
    
    const printName = _.memoize(_printName);
    
    printName("David");
    printName("John");
    

    清除整个记忆缓存(大卫和约翰):

    printName.cache.clear();
    

    显式删除单个记忆对象:

    printName.cache.delete("David");
    

    【讨论】:

      猜你喜欢
      • 2021-12-24
      • 2019-01-16
      • 1970-01-01
      • 2018-05-06
      • 2019-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多