js递归缓存方法

方法一: 普通递归缓存法

function fn(n){
  if(isFinite(n) && n>0 && n == Math.round(n)){ //不是无限数 && 是否大于0 && 取整  
    if(!(n in fn)){ //是否在fn缓存内
      if(n<=1){ //当n=1时,结果为1
        return 1
      }else{
        return fn[n] = n * fn(n-1); //计算得到的值存入fn缓存
      }
    }else{
      return fn[n]; //有的话就返回
    }
  }
}

方法二: 高阶函数缓存法

 function memorize(f){	//高阶函数
  var cache = {};
   return function(){
     var key = arguments.length + Array.prototype.join.call(arguments,",");
     if(key in cache){
       console.log(cache)	//打印缓存的值
       return cache[key];
     }else{
       return cache[key] = f.apply(this, arguments)	//没有缓存则执行函数求出值
     };
   }
 }

 function fn2(n){	//递归函数
   if(n<=1){
     return 1
   }else{
     return n*factorial(n-1);
   }
 }

 let factorial = memorize(fn2) //将函数变成参数传入高阶函数
 
 factorial(5)	//执行一次后 高阶函数的cache内就缓存了1~5对应的值

猜你喜欢

转载自blog.csdn.net/qq_41614928/article/details/95195296