How can one implement a cache supporting timeouts (TTL)
values in JavaScript using Lodash?
_.memorize
doesn't have a TTL
feature.
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 recommend using memoize()
for this. It defeats the purpose of memoization, which is to cache the results of a computation that never change, for a given set of inputs.
If you want to build a TTL cache, I would recommend looking at wrap(). Use this to wrap your functions with a generic function that does the caching and TTL checks.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With