Created
July 27, 2015 22:25
-
-
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.
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
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