Created
July 25, 2017 17:58
-
-
Save selfup/1112b78fb090822ddc9422d509d8de77 to your computer and use it in GitHub Desktop.
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
const fib = (num, cache = {}) => { | |
if (num < 2) return num; | |
// if the cached result exists, return the cached result | |
if (cache[num]) return cache[num]; | |
// otherwise, create a new entry in the cache with the new result | |
return Object.assign( | |
cache, | |
{ [num]: (fib(num - 1, cache) + fib(num - 2, cache)) }, | |
)[num]; | |
// ^^ and return the result so recursion can continue | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment