Skip to content

Instantly share code, notes, and snippets.

@wulftone
Created November 27, 2013 09:49
Show Gist options
  • Save wulftone/7673202 to your computer and use it in GitHub Desktop.
Save wulftone/7673202 to your computer and use it in GitHub Desktop.
Factorial function, recursive and cached for fast re-lookup.
(function(){
// Save a reference to the global object (`window` in the browser, `exports`
// on the server).
var root = this,
// Save the previous value of the `Factorial` variable, so that it can be
// restored later on, if `noConflict` is used.
previousFactorial = root.Factorial,
// The top-level namespace. All public Factorial classes and modules will
// be attached to this. Exported for both the browser and the server.
Factorial;
if (typeof exports !== 'undefined') {
Factorial = exports;
} else {
Factorial = root.Factorial = {};
}
// Depends on an external "memo" of the factorial value.
// This allows the factorial function to look up values
// that have already been calculated.
// "factorialMemo" is our "database" of values.
var factorialMemo = [],
factorial = function(n) {
if (n == 0 || n == 1)
return 1;
if (factorialMemo[n] > 0) {
console.log('Retrieving result from cache for factorial of', n);
return factorialMemo[n];
} else {
var result = factorial(n - 1) * n;
console.log('Assigning', result, 'to memo at', n);
return factorialMemo[n] = result;
}
},
factorialViaLoop = function(n) {
if (factorialMemo[n] > 0) {
console.log('Retrieving result from cache for factorial of', n);
return factorialMemo[n];
} else {
var rval = 1;
for (var i = 2; i <= n; i++) {
rval = rval * i;
console.log('Assigning', rval, 'to memo at', i);
factorialMemo[i] = rval;
}
return rval;
}
};
Factorial.memo = factorialMemo;
Factorial.recursive = factorial;
Factorial.loop = factorialViaLoop;
}).call(this);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment