Created
January 6, 2012 08:14
-
-
Save psiborg/1569635 to your computer and use it in GitHub Desktop.
JS Caching
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 fibonacci = (function () { | |
var cache = {}; | |
return function (n) { | |
if (cache[n]) { | |
return cache[n]; | |
} | |
//console.log("Solving for " + n); | |
var result; | |
if (n < 1) { | |
result = 0; | |
} | |
else if (n == 1) { | |
result = 1; | |
} | |
else { | |
// recursion | |
result = fibonacci(n - 2) + fibonacci(n - 1); | |
} | |
cache[n] = result; | |
return result; | |
} | |
})(); | |
for (var i = 0; i <= 20; i++) { | |
console.log(i + ' -> ' + fibonacci(i)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment