Lodash中memoize函数可以对一个函数进行缓存,返回一个被缓存过的函数,然后这个函数就只能被执行一次
案例:
const _ = require('lodash');
const test = ()=>{
console.log(123);
}
const memoizedTest = _.memoize(test);//返回一个被缓存的函数
console.log(memoizedTest());//只有这个被执行
console.log(memoizedTest());
console.log(memoizedTest());
console.log(memoizedTest());

模拟momeize函数
const memoize = (fn)=>{
let cache = {};
return ()=>{
if(!cache[fn]){//一开始cache没有[fn]这个属性,第一次执行之前给cache添加了这个属性,通过是否有[fn]这个内容,决定是否运行fn这个函数。
cache[fn] = fn;
fn();
return;
}
}
}
const res = memoize(test);
console.log(res());
console.log(res());
console.log(res());
console.log(res());

Lodash memoize 函数详解
本文介绍了 Lodash 中的 memoize 函数及其工作原理,通过示例代码展示了如何使用 memoize 对函数进行缓存,避免重复计算。同时提供了一个简易的 memoize 实现方案。
3562

被折叠的 条评论
为什么被折叠?



