Created
May 30, 2017 21:25
-
-
Save kyleshevlin/c490348fc2852b453eeb34d2d3e8f495 to your computer and use it in GitHub Desktop.
memoized fibonacci sequence for posterity
This file contains 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 memoizedFibonacci (n) { | |
if (!memoizedFibonacci.memo) { | |
memoizedFibonacci.memo = {} | |
} | |
if (memoizedFibonacci.memo[n]) { | |
return memoizedFibonacci.memo[n] | |
} else { | |
let value | |
if (n < 2) { | |
value = n | |
} else { | |
value = memoizedFibonacci(n - 1) + memoizedFibonacci(n - 2) | |
} | |
memoizedFibonacci.memo[n] = value | |
return value | |
} | |
} | |
console.log(memoizedFibonacci(10)) | |
console.log(memoizedFibonacci(20)) | |
console.log(memoizedFibonacci.memo) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment