Skip to content

Instantly share code, notes, and snippets.

@hascode
Created October 15, 2014 07:36
Show Gist options
  • Save hascode/83692b79671583d06ee7 to your computer and use it in GitHub Desktop.
Save hascode/83692b79671583d06ee7 to your computer and use it in GitHub Desktop.
JavaScript Memoization
var fib = function(n){
return (n<2) ? 1 : fib(n-1) + fib(n-2);
}
var calc = function(numbers){
var self = this;
numbers.forEach(function(n){
if(!self.cache){
self.cache = {};
}
if(self.cache[n]){
console.log('from cache: '+n);
return self.cache[n];
}
return self.cache[n] = fib(n);
});
};
calc([1,4,3,4]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment