Memoize a function
Cache results by argument so expensive pure functions only run once per distinct input.
- JavaScript
- GreenSnippets
- MIT
- Executed with Node.js 22
function memoize(fn, getKey = (...args) => JSON.stringify(args)) {
const cache = new Map();
return function memoized(...args) {
const key = getKey(...args);
if (cache.has(key)) return cache.get(key);
const value = fn.apply(this, args);
cache.set(key, value);
return value;
};
}Example / expected output
const slowSquare = memoize((n) => n * n);
slowSquare(9); // computed
slowSquare(9); // returned from cacheHow it works
Only memoize pure functions. The default key is the JSON of the arguments; pass getKey for arguments that are not serializable. The cache is unbounded, so for long-running processes add an eviction policy such as a size cap.
Related snippets
- JavaScript Tested
Run a function only once
Wrap a function so it executes on the first call and returns the same result afterwards.
- TypeScript Tested
Debounce with preserved argument types
A debounce function whose returned function keeps the parameter types and exposes cancel() and flush().
- JavaScript Tested
Curry a function
Turn a multi-argument function into one that can be called a few arguments at a time.
- JavaScript Tested
Compose and pipe functions
Chain single-argument functions left-to-right with pipe, or right-to-left with compose.

