Skip to content

Instantly share code, notes, and snippets.

@selfup
Created July 25, 2017 17:58
Show Gist options
  • Save selfup/1112b78fb090822ddc9422d509d8de77 to your computer and use it in GitHub Desktop.
Save selfup/1112b78fb090822ddc9422d509d8de77 to your computer and use it in GitHub Desktop.
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