// used to demonstrate the factorial of n
data stored on the step of the calculation, the next calculation time to determine whether there were last performed, and if there is direct access to the stored value is calculated and then the next step
// n! n*(n-1)*....*2*1
// 0! = 1
// n! = n*(n-1)!
// achieve before memory var count = 0 // number of executions function factorial(n) { count ++ if(n == 0 || n==1) { return 1 } return n * factorial(n-1) } for(var i=1; i<=5; i++) { console.log(factorial(i)) }
// realize the memory var COUNT = 0 // number of executions var Cache = [] // save up --- performed such data calculated from the 5, 6 and then only when the factorial performing 6x5! Is the factorial of 5 directly from the stored data function factorial(n) { count++ IF (cache [n-]) { // if the cache (cache value) direct access to the value in the buffer return cache[n] The else {} // is not calculated if (n == 0 || n == 1) { cache[0] = 1 cache[1] = 1 return 1 } else { cache[n] = n * factorial(n - 1) return cache[n] } } } console.time('3') console.log(factorial(3)) console.timeEnd ( '3') console.log('=================') console.time('4') console.log(factorial(4)) console.timeEnd ( '4')
// 优化 function factorial(n) { if (n == 0 || n == 1) { return 1 } else { return n * factorial(n - 1) } } // wrapper function function Memorize (Fn) { var Cache = {} // used to store the value of the object return function () { var key = + Array.prototype.join.call The arguments.length (arguments) // achieve unique key identification IF (Cache [Key]) { return Cache [Key] } The else { // use argumens array parameter to obtain a class of Cache [Key] = fn.apply ( the this , arguments) return Cache [Key] } } } var newF = memorize(factorial)