一、函数防抖
利用缓存池: 对象,数组都行(实际上还是将数组元素索引作为箭名的方式)
function factorial1 (n) {
if( n === 0 || n === 1 ){
return 1
}
return n * factorial1 (n - 1)
}
//使用函数记忆
function factorial2 (n) {
let time = 0,
cache = [];
function compute(n){
time++;
if( cache[n] ){
return cache[n]
}
if(n === 0 || n ===1){
cache[n] = 1
return cache[n]
}
if( !cache[n] ){
cache[n] = n * compute(n - 1)
return cache[n]
}
}
let result = compute(n)
console.log(time, cache)
return result
}
console.time('first')
factorial1(90)
console.timeEnd('first')
console.time('second')
factorial2(90)
console.timeEnd('second')
二、函数记忆封装
function factorial(n){
if(n === 0 || n === 1){
return 1
}
return n * factorial(n - 1)
}
function memory(fn){
let cache = {};
return function(){
let keyName = [].join.call(arguments);
return cache[keyName] = cache[keyName] || fn.apply(fn, arguments)
}
}
let test = memory(factorial);
console.log( test(6) )
对斐波那契数列函数进行记忆封装
function fab(n){
return n <= 2 ? 1 : fab( n - 1 ) + fab( n -2 )
}
function memory(fn){
let cache = {};
return function(){
let keyName = [].join.call(arguments);
return cache[keyName] = cache[keyName] || fn.apply(fn, arguments)
}
}
let test = memory(fab);
console.log( test(6) )