缓存函数
应用场景 :递归 、大量数据计算、
var times2 = 0;function factorial2(n) {times2++;if (n === 0 || n === 1) {return 1;}return n * factorial2(n - 1);}var times = 0,cache = [];function factorial(n) {times++;if (cache[n]) {return cache[n];}if (n === 0 || n === 1) {cache[0] = 1;cache[1] = 1;return 1;}return cache[n] = n * factorial(n - 1);}console.time('未使用缓存函数');console.log(factorial2(6));console.timeEnd('未使用缓存函数');console.time('使用缓存函数');console.log(factorial(6));console.timeEnd('使用缓存函数');console.log('cache',cache);

封装缓存函数
var times1 = 0;
function factorial1(n) {
times1++;
if (n === 0 || n === 1) {
return 1;
}
return n * factorial1(n - 1);
}
//封装缓存函数
function memorize(fn) {
var cache = {};
return function () {
var k = [].join.call(arguments, ',');
return cache[k] = cache[k] || fn.apply(this, arguments);
}
}
console.time('未使用缓存函数');
console.log(factorial1(5));
console.timeEnd('未使用缓存函数');
console.time('使用缓存函数1');
console.log(memorize(factorial2)(5));
console.timeEnd('使用缓存函数1');

