Implementing a Generic Memoize Function
What you'll learn: How to create a reusable higher-order function that adds memoization to any function automatically.
The Core Idea
Instead of manually adding caching logic to every function you want to memoize, you can write one generic memoize() function that wraps any other function and handles the caching for you. It takes a function as input and returns a new, memoized version of that function.
Think of it like a wrapper machine: you feed in any function, and it spits out that same function with a built-in memory system.
Building the Generic Memoize Function
function memoize(fn) {
const cache = new Map();
return function(...args) {
// Create a cache key from arguments
const key = JSON.stringify(args);
// Return cached result if available
if (cache.has(key)) {
return cache.get(key);
}
// Call original function and cache result
const result = fn(...args);
cache.set(key, result);
return result;
};
}
// Use it with ANY function:
const memoizedAdd = memoize((a, b) => {
console.log('Computing...');
return a + b;
});
memoizedAdd(2, 3); // Logs "Computing...", returns 5
memoizedAdd(2, 3); // Returns 5 (no log, uses cache)
The memoize function creates a private cache and returns a wrapper function that checks the cache before calling the original function. We use JSON.stringify(args) to create a cache key from all arguments.
This works with any pure function—factorial calculators, API data transformers, complex computations—without rewriting caching logic each time.
Key Takeaway: A generic memoize function is a higher-order function that wraps any function with caching logic, making memoization reusable and declarative across your codebase.