記憶函數功能
阿新 • • 發佈:2017-12-03
lan proto his tor join nts meta func col
使用JS記憶函數功能,能夠有效提供代碼的性能。
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>記憶函數</title> 6 </head> 7 <body> 8 9 </body> 10 </html> 11 <script> 12 /** 13 * 記憶函數 14 * */ 15 functionmemoize(fn){ 16 return function(){ 17 var propertyName; 18 fn.storage = fn.storage || {}; 19 20 propertyName = Array.prototype.join.call(arguments,"|"); 21 22 if(propertyName in fn.storage){ 23 return fn.storage[propertyName];24 }else{ 25 fn.storage[propertyName] = fn.apply(this,arguments); 26 return fn.storage[propertyName]; 27 } 28 } 29 } 30 31 /** 32 * 計算階乘的函數 33 * @param num 34 * @returns {number} 35 */ 36 function getFactorial(num){37 var result = 1, 38 index = 1; 39 for(;index <=num;index++){ 40 result *= index; 41 } 42 return result; 43 } 44 45 var calcFn = memoize(getFactorial); 46 debugger; 47 calcFn(5); 48 calcFn(5); 49 50 </script>
記憶函數功能