function lazyFunction(fn) { | |
let cache; | |
return function() { | |
if (!cache) { | |
cache = fn.apply(this, arguments); // 执行函数并缓存结果 | |
} | |
return cache; // 返回缓存的结果 | |
}; | |
} | |
// 使用示例 | |
const expensiveCalculation = () => { | |
console.log('Calculating the result...'); | |
return Math.random(); // 假设这是一个耗时的计算 | |
}; | |
const lazyExpensiveCalculation = lazyFunction(expensiveCalculation); | |
console.log(lazyExpensiveCalculation()); // 输出 "Calculating the result..." 和一个随机数 | |
console.log(lazyExpensiveCalculation()); // 不再输出 "Calculating the result...",而是直接返回之前的随机数 |
正文完