JS编程建议——66：使用函数实现历史记录

0
2
0
1. 云栖社区>
2. 博客>
3. 正文

## JS编程建议——66：使用函数实现历史记录

zhanginzaghi 2017-12-18 09:28:04 浏览1306

var fibonacci = function(n) {

return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2);

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

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

}

0: 0
1: 1
2: 1
3: 2
4: 3
5: 5
6: 8
7: 13
8: 21
9: 34
10: 55

var fibonacci = ( function() {

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

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

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

}

var memoizer = function(memo, formula) {

var recur = function(n) {
var result = memo[n];
if( typeof result !== 'number') {
result = formula(recur, n);
memo[n] = result;
}
return result;
};
return recur;

};

var fibonacci = memoizer([0, 1], function(recur, n) {

return recur(n - 1) + recur(n - 2);

});

var factorial = memoizer([1, 1], function(recur, n) {

return n * recur(n - 1);

});

zhanginzaghi
+ 关注