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

javascriptsnippet
13 lines
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;
  };
}

How the snippet works

The working surface is the functions memoize and memoized — everything else is wiring.

Watch out for

  • The guard entry && now - entry.at < ttlMs short-circuits the flow with an early return when its condition holds.

Applying it

The primary signature is export function memoize(fn, ttlMs = 60000)

memoize is what another module would consume; nothing else here is load-bearing for callers.

Statements that matter

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;
};
const cache = new Map();

Interactive Tools for This Topic

FAQ

What has to be installed first?
Nothing — the runtime itself provides everything the code touches. The file defines `memoize`, `memoized` at load time.