面试题 Interview Question
实现一个函数
memoize
,用于缓存纯函数的计算结果以提高性能。
Implement a functionmemoize
to cache the results of a pure function in order to improve performance.
要求 Requirements
-
memoize(fn)
接收一个纯函数fn
,返回一个具有缓存能力的新函数
memoize(fn)
takes a pure functionfn
and returns a new function with caching capability. -
如果使用相同的参数再次调用该函数,应从缓存中返回结果,而非重新计算
When called again with the same arguments, it should return the cached result instead of re-executingfn
. -
要求:
- 支持任意数量的参数(包括多个基本类型)
Support arbitrary number of arguments (including multiple primitives) - 不使用
this
,保持纯函数风格
Do not usethis
; stick to a pure functional style - 使用
Map
或WeakMap
实现缓存(推荐)
UseMap
orWeakMap
for caching (preferred)
- 支持任意数量的参数(包括多个基本类型)
参考答案 Reference Solution
function memoize(fn) {
const cache = new Map();
return function (...args) {
const key = JSON.stringify(args);
if (cache.has(key)) {
return cache.get(key);
}
const result = fn(...args);
cache.set(key, result);
return result;
};
}
示例 Example
const slowAdd = (a, b) => {
console.log('计算中... Computing...');
return a + b;
};
const memoizedAdd = memoize(slowAdd);
console.log(memoizedAdd(1, 2)); // 计算中... → 3
console.log(memoizedAdd(1, 2)); // 直接返回缓存 → 3
面试考察点 Interview Focus
- 对闭包和缓存机制的理解
Understanding of closures and caching mechanics - 参数序列化处理技巧
Ability to serialize arguments reliably for use as cache keys - 内存优化与性能优化意识
Awareness of memory and performance optimization techniques