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.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742283060a4414846.html
评论列表(0条)