Skip to content

Instantly share code, notes, and snippets.

@tjeastmond
Created September 2, 2015 13:36
Show Gist options
  • Save tjeastmond/078eadea3d045dfcaaa9 to your computer and use it in GitHub Desktop.
Save tjeastmond/078eadea3d045dfcaaa9 to your computer and use it in GitHub Desktop.
var memoizer = function(memo, func) {
var recur = function(n) {
var result = memo[n];
if (typeof result !== 'number') {
result = func(recur, n);
memo[n] = result;
}
return result;
};
return recur;
};
var fibonacci = memoizer([0, 1], function(recur, n) {
return recur(n - 1) + recur(n - 2);
});
var factorial = memoizer([1, 1], function(recur, n) {
return n * recur(n - 1);
});
console.log('fibonacci(3):', fibonacci(3));
console.log('factorial(10):', factorial(10));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment