function memoize(fn) {
const cache = {};
return function(x) {
if (x in cache) return cache[x];
return (cache[x] = fn(x));
};
}
const memoSqrt = memoize(Math.sqrt);
memoSqrt(25); // 5 (computed)
memoSqrt(25); // 5 (cached)Memoization caches the result of a function call to avoid redundant computation.
Memoization caches function results to avoid recomputation. This is useful for expensive operations.
Challenge: Implement a memoize function that caches results for single-argument functions. Repeated calls with the same argument should return cached results.