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([1, 1], function (shell, n) {
return shell(n - 1) + shell(n - 2);
});
var factorial = memoizer([1, 1], function (shell, n) {
return n * shell(n - 1);
});
function test(n) {
for (var i = 1; i <= n; i++) {
fibonacci(n);
factorial(n);
}
}
说明: 当执行test(n)时,该思路就能大幅提升性能!