javascript - Building a cache with TTL feature in Lodash - Stack Overflow

How can one implement a cache supporting timeouts (TTL) values in JavaScript using Lodash? _.memorize d

How can one implement a cache supporting timeouts (TTL) values in JavaScript using Lodash?

_.memorize doesn't have a TTL feature.

How can one implement a cache supporting timeouts (TTL) values in JavaScript using Lodash?

_.memorize doesn't have a TTL feature.

Share Improve this question edited Jun 21, 2015 at 13:23 Bk_ 999 bronze badges asked Jun 21, 2015 at 12:58 Ali SalehiAli Salehi 6,99911 gold badges53 silver badges77 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 4

As an example Adam's answer to use the _.wrap method you can do:

var myExpensiveFunction = _.wrap(myExpensiveFunction, function(originalFunction, param1) {
  if (/* data is in cache and TTL not expired */){
      // return cachedValue
  } else {
      // run originalFunction(param1) and save cachedValue
      // return cachedValue;
  }
});

If your expensive function returns a promise, don't forget to return a resolved promise instead of cachedValue directly if cache exists

I wouldn't remend using memoize() for this. It defeats the purpose of memoization, which is to cache the results of a putation that never change, for a given set of inputs.

If you want to build a TTL cache, I would remend looking at wrap(). Use this to wrap your functions with a generic function that does the caching and TTL checks.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742283060a4414846.html

相关推荐

  • javascript - Building a cache with TTL feature in Lodash - Stack Overflow

    How can one implement a cache supporting timeouts (TTL) values in JavaScript using Lodash? _.memorize d

    1天前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信