Skip to content

Instantly share code, notes, and snippets.

@psiborg
Created January 6, 2012 08:14
Show Gist options
  • Save psiborg/1569635 to your computer and use it in GitHub Desktop.
Save psiborg/1569635 to your computer and use it in GitHub Desktop.
JS Caching
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