Memoization & Currying
Two powerful functional programming techniques. Learn how to cache expensive function calls (Memoization) and break down complex functions into smaller, reusable pieces (Currying).
Optimization and Transformation
**Memoization** is a caching strategy. It allows a function to 'remember' its previous inputs and outputs. If it sees the same input again, it returns the cached answer instantly instead of recomputing it.
**Currying** is a structural transformation. It converts a function that takes multiple arguments (f(a, b)) into a sequence of functions that each take a single argument (f(a)(b)).
Performance and Reusability
Use Memoization to speed up slow, CPU-heavy algorithms or redundant API calls. If a calculation takes 2 seconds to run, running it twice shouldn't take 4 seconds-it should take 2.001 seconds.
Use Currying to create highly reusable 'factory' functions. By currying a logging function log(level)(message), you can easily create specialized versions like const logError = log('ERROR') and use it everywhere.
Writing them in JavaScript
Both patterns rely heavily on **Closures** (functions returning functions and remembering their lexical scope).
**Memoization:**
javascript
function memoize(fn) {
const cache = {};
return function(x) {
if (cache[x]) return cache[x];
const result = fn(x);
cache[x] = result;
return result;
}
}
**Currying:**
javascript
function multiply(a) {
return function(b) {
return a * b;
}
}
// Or in ES6:
const multiply = a => b => a * b;
The Cacher & The Curry
Explore both concepts below. In the Memoization panel, notice how the first calculation takes time, but subsequent identical calls are instantaneous. In the Currying panel, watch how passing one argument creates a brand new function waiting for the next.
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- **Memoization** caches function results. If the same inputs are provided again, it returns the cached answer instantly.
- Memoization trades memory (storing the cache) for speed (skipping computation).
- **Currying** transforms a function of multiple arguments into a chain of single-argument functions:
f(a)(b)(c). - Currying is excellent for creating specialized, reusable 'factory' functions from generic ones.
- Both patterns rely on **Closures** to remember state (the cache object, or the earlier arguments) across executions.
Done with this concept?
Mark it complete to track your progress. No login needed.