A Simple Memoization Example
What you'll learn: How to build a basic memoized function that caches results based on input arguments to avoid redundant calculations.
Now that you understand what memoization is, let's build a simple example. The core pattern involves wrapping a function with a cache—typically an object or Map—that stores results keyed by the function's arguments.
The Basic Pattern
Imagine you have an expensive calculation like computing factorial numbers. Without memoization, calling factorial(5) multiple times repeats the same work. With memoization, you compute it once and retrieve the cached result on subsequent calls:
function memoize(fn) {
const cache = {};
return function(arg) {
if (arg in cache) {
console.log('Returning cached result for:', arg);
return cache[arg];
}
console.log('Computing result for:', arg);
const result = fn(arg);
cache[arg] = result;
return result;
};
}
// Original expensive function
function factorial(n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
const memoizedFactorial = memoize(factorial);
console.log(memoizedFactorial(5)); // Computing result for: 5 → 120
console.log(memoizedFactorial(5)); // Returning cached result for: 5 → 120
console.log(memoizedFactorial(6)); // Computing result for: 6 → 720
How It Works
The memoize wrapper creates a closure with a cache object. Before calling the original function, it checks if the result for that argument exists. If yes, return it immediately. If no, compute it, store it, and return it.
This simple version works for single-argument functions. Multi-argument memoization requires serializing arguments into cache keys—a topic you'll explore later.
Key Takeaway: A basic memoized function wraps the original with a cache lookup: check the cache first, compute and store if missing, and return the result—turning repeated calls into instant retrievals.