Created
November 27, 2013 09:49
-
-
Save wulftone/7673202 to your computer and use it in GitHub Desktop.
Factorial function, recursive and cached for fast re-lookup.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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