0 day streak
javascript / intermediate
Snippet

Functional Memoization for Performance

Memoization is an optimization technique where you store the results of expensive function calls and return the cached result when the same inputs occur again.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
const memoize = (fn) => {
const cache = new Map();
return (arg) => {
if (cache.has(arg)) return cache.get(arg);
const result = fn(arg);
cache.set(arg, result);
return result;
};
};
const heavyMath = n => { console.log('Computing...'); return n * 2; };
const fastMath = memoize(heavyMath);
console.log(fastMath(10)); // Computing... 20
console.log(fastMath(10)); // 20 (cached)
Breakdown
1
const cache = new Map();
Uses a Map to store previously computed results indexed by their argument.
2
return (arg) => {
Returns a new closure that has access to the private cache.
3
if (cache.has(arg)) return cache.get(arg);
Checks if the computation was already done for this specific argument.
4
cache.set(arg, result);
Stores the new result in the cache for future use.