说说如何实现函数缓存
# 是什么
定义: 将函数运算过的结果进行缓存,本质是用空间(存储)换时间(计算过程)
# 如何实现
- 闭包
- 高阶函数
- 柯里化
# 闭包
function fn() {
let count = 1;
function add() {
count += 1;
return count;
}
return {
add,
};
}
let f = fn();
let result = f.add();
console.log(result);
# 高阶函数
const memoize = function(func, content) {
let cache = Object.create(null);
content = content || this;
return (...key) => {
if (!cache[key]) {
cache[key] = func.apply(content, key);
}
return cache[key];
};
};
const calc = memoize(add);
const num1 = calc(100, 200);
const num2 = calc(100, 200); // 缓存得到的结果
# 柯里化
# 原理
// 函数柯里化
var add2 = function (x) {
//**返回函数**
return function (y) {
return x+y;
}
}
add2(3)(4) //7
上次更新: 2021/12/19, 18:05:42