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.
Code
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 < ttlMsshort-circuits the flow with an earlyreturnwhen 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
Duration ConverterConvert between human durations like 1w2d3h45m and total seconds, hours, and minutes with negative support.Duration HumanizerTurn a number of seconds into a readable duration such as 1 day, 2 hours, 3 minutes, and show the equivalent in minutes and hours.HAR Waterfall AnalyzerInspect HTTP Archive (HAR 1.2) JSON files locally to summarize total requests, status codes, MIME types, slowest calls, and timing waterfalls.Cache-Control BuilderCompose a valid Cache-Control header from directives such as no-store, private, max-age, and immutable.
FAQ
- What has to be installed first?
- Nothing — the runtime itself provides everything the code touches. The file defines `memoize`, `memoized` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.