Skip to content

Instantly share code, notes, and snippets.

@recidive
Created July 6, 2016 02:03
Show Gist options
  • Save recidive/85a653e87adae3207b77d51933bd40e6 to your computer and use it in GitHub Desktop.
Save recidive/85a653e87adae3207b77d51933bd40e6 to your computer and use it in GitHub Desktop.
// Simple unoptimized calculator for the nth fibonacci number.
const fibonacci = n => (n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2))
console.time('fibonacci')
console.log(fibonacci(20))
console.timeEnd('fibonacci')
// A single argument function memoization wrapper.
const memoize = func => {
const cache = {}
return arg => (arg in cache) ? cache[arg] : (cache[arg] = func(arg))
}
// Apply memoization to the fibonacci function.
const memoizedFibonacci = memoize(fibonacci)
console.time('memoizedFibonacci')
console.log(memoizedFibonacci(20))
console.timeEnd('memoizedFibonacci')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment