Skip to content

Instantly share code, notes, and snippets.

@alfredmyers
Last active August 29, 2015 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alfredmyers/3a35d5b1c53a0ba029d7 to your computer and use it in GitHub Desktop.
Save alfredmyers/3a35d5b1c53a0ba029d7 to your computer and use it in GitHub Desktop.
Factorial with memoization
var factorial = (function () {
var cache = [1];
return function factorial(n) {
if(n < 0) {
return Infinity;
}
n = parseInt(n);
if (n < cache.length) {
return cache[n];
}
for (var i = cache.length; i <= n; i++) {
cache[i] = i * cache[i - 1];
}
return cache[n];
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment