Memoize With a Time to Live

Cache a function's result by argument key with an expiry, so expensive pure calls are reused briefly and stale values eventually recompute.

JavascriptData Fetching

Code

snippet
export function memoize(fn, ttlMs = 60000) {
  const cache = new Map();
  return function memoized(key, ...rest) {
    const now = Date.now();
    const entry = cache.get(key);
    if (entry && now - entry.at < ttlMs) {
      return entry.value;
    }
    const value = fn(key, ...rest);
    cache.set(key, { value, at: now });
    return value;
  };
}