JavaScript Closure Memorization

bkjs626發表於2017-11-03

js閉包記憶化程式設計學習

利用記憶化使遞迴次數大大減少。
以Fibonacci數列為例:

var fibonacci = function(){
    var memo = [0, 1];
    var fib = function(i){
        var result = memo[i];
        if(typeof result !== 'number'){
            result = fib[i-1]+fib[i-2];
            memo[i] = result;
        }
        return result;  
    }
    return fib;
}();

for(var i = 0; i < 10; ++i){
    console.log(fibonacci(i));
}

進一步封裝:

var memoizer = function(memo, fundamental){
    var shell = funciton(n){
        var result = memo[n];
        if(typeof result !== 'number'){
            result = fundamental(shell, n);
            memo[n] = result;
        }
        return result;
    };
    return shell;
}

//斐波那契數列
var fibonacci = memoizer([0,1], function(shell, n){
    return shell(n - 1)+shell(n - 2);
})  

//階乘
var factorial = memoizer([1,1], function(shell, n){
    return shell(n-1)*n; 
})

相關文章