/** * @param {Function} fn */ function memoize(fn) { return function() { } } /** * let callCount = 0; * const memoizedFn = memoize(function (a, b) { * callCount += 1; * return a + b; * }) * memoizedFn(2, 3) // 5 * memoizedFn(2, 3) // 5 * console.log(callCount) // 1 */通过这个格式优化一下
时间: 2023-10-21 22:42:30 浏览: 36
```javascript
function memoize(fn) {
const cache = {};
return function(...args) {
const key = JSON.stringify(args);
if (cache.hasOwnProperty(key)) {
return cache[key];
}
const result = fn.apply(this, args);
cache[key] = result;
return result;
};
}
let callCount = 0;
const memoizedFn = memoize(function(a, b) {
callCount += 1;
return a + b;
});
console.log(memoizedFn(2, 3)); // 5
console.log(memoizedFn(2, 3)); // 5
console.log(callCount); // 1
```
在这个示例中,我们将 memoize 函数的实现用上面之前提到的代码替换,并在后面添加了完整的示例代码。memoizedFn 是通过 memoize 函数创建的记忆化版本的函数。我们通过调用 memoizedFn(2, 3) 来测试记忆化的效果。第一次调用时,会计算结果并缓存起来,第二次调用时则直接返回缓存的结果。最后,我们打印出 callCount 的值,验证了函数只被调用了一次。
希望这次的优化能满足你的需求!如果还有其他问题,请随时问我。