Last active
August 29, 2015 14:25
-
-
Save alfredmyers/3a35d5b1c53a0ba029d7 to your computer and use it in GitHub Desktop.
Factorial with memoization
This file contains 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
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