JavaScript Factorial with Memoization

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 factorial = memoizer([1,1], function (recur, n) {
     return n * recur(n - 1);
});
 
document.writeln(factorial(10)); // 3628800

credit: Crockford, Douglas. JavaScript: The Good Parts, p.45. O’Reilly 2008

Leave a Reply

You must be logged in to post a comment.