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.
2 Answers
Reset to default 4As 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
版权声明:本文标题:javascript - Building a cache with TTL feature in Lodash - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742283060a2446451.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论