Last active
January 19, 2018 00:59
-
-
Save MichaelSitter/3a09fce9f2b95eeb38c8c28d63142eeb to your computer and use it in GitHub Desktop.
Memoized fib
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 fib(n) { | |
var res = {} | |
function step(t) { | |
if (res[t]) { | |
return res[t] | |
} | |
if (t <= 1) { | |
res[t] = t | |
} else { | |
res[t] = step(t-1) + step(t-2) | |
} | |
return res[t] | |
} | |
return step(n) | |
} | |
function naiveFib(n) { | |
if (n <= 1) { | |
return n | |
} else { | |
return naiveFib(n-1) + naiveFib(n-2) | |
} | |
} | |
var t0 = performance.now() | |
console.log(fib(30)) | |
var t1 = performance.now() | |
console.log(`took ${t1-t0}ms`) | |
t0 = performance.now() | |
console.log(naiveFib(30)) | |
t1 = performance.now() | |
console.log(`took ${t1-t0}ms`) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment