Creating a cache with TTL function in Lodash

How can I implement a cache that supports timeouts of (TTL)values ​​in JavaScript using Lodash?

_.memorizedoes not have a function TTL.

+4
source share
2 answers

I would not recommend using memoize()for this. He defeats the goal of memoization, which is to cache computational results 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 performs cache and TTL checks.

+2
source

_.wrap, :

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;
  }
});

, cachedValue ,

0

All Articles