Skip to content

Instantly share code, notes, and snippets.

@wesleybliss
Created August 31, 2018 19:43
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save wesleybliss/5028ed066f5b7053f5a5d1ea584e3c7a to your computer and use it in GitHub Desktop.
Memoized Fibonacci
const fib = n => (n < 2) ? n : fib(n - 1) + fib(n - 2)
const fibSexy = (() => {
const cache = {}
const f = n => {
const value = (n in cache)
? cache[n]
: (n < 2) ? n : f(n - 1) + f(n - 2)
if (!(n in cache)) cache[n] = value
return value
}
return f
})()
console.time('fib')
console.log(
fib(10)
)
console.timeEnd('fib')
console.time('fibSexy')
console.log(
fibSexy(10)
)
console.timeEnd('fibSexy')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment