01 / Foundation
Understand the concept
Memoization is an optimization technique where function results are cached so repeated calls with the same input return the cached value instead of recalculating.
Memoization is widely used in JavaScript, React, dynamic programming, and performance optimization.
02 / Implementation
Memoization Example
memoization.js
function memoize(fn) {
const cache = {};
return function (num) {
if (cache[num]) {
console.log("Returning from cache");
return cache[num];
}
console.log("Calculating...");
cache[num] = fn(num);
return cache[num];
};
}
const add200 = memoize((num) => num + 200);
console.log(add200(20));
console.log(add200(20));
console.log(add200(30));04 / Interview