记忆 - 斐波那契数列

var memoizer = function(memo, fundamental) {

        var shell = function(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);

});

for (var i = 0; i <= 10; i += 1) {

    document.writeln('//' + i + ': ' + fibonacci(i) + '<br/>');

}

 

你可能感兴趣的:(记忆)