一、函数防抖
    利用缓存池: 对象,数组都行(实际上还是将数组元素索引作为箭名的方式)

    1. function factorial1 (n) {
    2. if( n === 0 || n === 1 ){
    3. return 1
    4. }
    5. return n * factorial1 (n - 1)
    6. }
    7. //使用函数记忆
    8. function factorial2 (n) {
    9. let time = 0,
    10. cache = [];
    11. function compute(n){
    12. time++;
    13. if( cache[n] ){
    14. return cache[n]
    15. }
    16. if(n === 0 || n ===1){
    17. cache[n] = 1
    18. return cache[n]
    19. }
    20. if( !cache[n] ){
    21. cache[n] = n * compute(n - 1)
    22. return cache[n]
    23. }
    24. }
    25. let result = compute(n)
    26. console.log(time, cache)
    27. return result
    28. }
    29. console.time('first')
    30. factorial1(90)
    31. console.timeEnd('first')
    32. console.time('second')
    33. factorial2(90)
    34. console.timeEnd('second')

    二、函数记忆封装

    1. function factorial(n){
    2. if(n === 0 || n === 1){
    3. return 1
    4. }
    5. return n * factorial(n - 1)
    6. }
    7. function memory(fn){
    8. let cache = {};
    9. return function(){
    10. let keyName = [].join.call(arguments);
    11. return cache[keyName] = cache[keyName] || fn.apply(fn, arguments)
    12. }
    13. }
    14. let test = memory(factorial);
    15. console.log( test(6) )
    1. 对斐波那契数列函数进行记忆封装
    1. function fab(n){
    2. return n <= 2 ? 1 : fab( n - 1 ) + fab( n -2 )
    3. }
    4. function memory(fn){
    5. let cache = {};
    6. return function(){
    7. let keyName = [].join.call(arguments);
    8. return cache[keyName] = cache[keyName] || fn.apply(fn, arguments)
    9. }
    10. }
    11. let test = memory(fab);
    12. console.log( test(6) )