Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Building a cache with TTL feature in Lodash

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

_.memorize doesn't have a TTL feature.

like image 322
Ali Salehi Avatar asked Jun 21 '15 12:06

Ali Salehi


2 Answers

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

like image 94
Bruno Peres Avatar answered Nov 20 '22 23:11

Bruno Peres


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.

like image 2
Adam Boduch Avatar answered Nov 20 '22 21:11

Adam Boduch