JavaScript Interview Question #119
What is memoization?
Closures, Prototypes, Classes & Advanced Functions Mid-Level Intermediate
Quick Interview Answer
Memoization is an optimization technique that caches the result of a function for previously seen inputs so repeated calls can reuse the cached result instead of recalculating it.
Detailed Explanation
Memoization is an optimization technique that caches the result of a function for previously seen inputs so repeated calls can reuse the cached result instead of recalculating it.
It is most appropriate for expensive computations whose output is determined by the input. Cache size, invalidation, object-key semantics, and memory retention must be considered in real applications.
Code Example
function memoizeSquare() {
const cache = new Map();
return n => {
if (cache.has(n)) {
return cache.get(n);
}
const result = n * n;
cache.set(n, result);
return result;
};
}
const square = memoizeSquare();
console.log(square(10));