admin管理员组

文章数量:1332394

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.

本文标签: javascriptBuilding a cache with TTL feature in LodashStack Overflow