记忆 - 阶乘函数

 1 var memoizer = function(memo, fundamental) {

 2         var shell = function(n) {

 3                 var result = memo[n];

 4                 if (typeof result !== 'number') {

 5                     result = fundamental(shell, n);

 6                     memo[n] = result;

 7                 }

 8                 return result;

 9             };

10         return shell;

11     };

12 

13 //阶乘函数

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

15     return n * shell(n - 1);

16 });

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

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

19 }

你可能感兴趣的:(函数)