Memoize caches kết quả function theo argument key, tránh tính toán lại những lần sau.
js
function memoize(fn) {
const cache = new Map();
return (...args) => {
const key = JSON.stringify(args);
if (cache.has(key)) return cache.get(key);
const result = fn(...args);
cache.set(key, result);
return result;
};
}Lưu ý: JSON.stringify chậm cho args lớn.
Production dùng WeakMap cho object args, LRU cache giới hạn size.