Skip to content

Instantly share code, notes, and snippets.

@aldraco
Created July 27, 2015 22:25
Show Gist options
  • Save aldraco/dba96dcb861c4bc4296e to your computer and use it in GitHub Desktop.
Save aldraco/dba96dcb861c4bc4296e to your computer and use it in GitHub Desktop.
A memozation of Fibonacci, implemented for a CodeEval challenge but preserved here for reference.
function Fibonacci(n) {
// finds the fibonacci number
// base case: 0, 1 for F(0) and F(1)
if (n === 0) {
return 0;
} else if (n === 1) {
return 1;
} else {
return Fibonacci(n-1) + Fibonacci(n-2);
}
}
Function.prototype.memoize = Function.prototype.memoize || function() {
var self = this, cache = {};
return function(arg) {
if (cache[arg]) {
return cache[arg];
} else {
return cache[arg] = self(arg);
}
}
}
var memoedFib = Fibonacci.memoize();
console.log('memoed!', memoedFib(12)); // will print 144
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment