Created
October 15, 2014 07:36
-
-
Save hascode/83692b79671583d06ee7 to your computer and use it in GitHub Desktop.
JavaScript Memoization
This file contains hidden or 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 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