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.
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; }; }Note: JSON.stringify is slow for large arguments. In production, use WeakMap for object arguments and an LRU cache with a size limit.