Created
July 22, 2019 12:39
-
-
Save janneuman/702239d202581574fe1c9c76658f35a7 to your computer and use it in GitHub Desktop.
Optimized version of fib function
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
let i = 0; | |
function fib(num) { | |
if (num <= 1) { | |
return 1; | |
} | |
i++; | |
return fib(num - 1) + fib(num - 2); | |
} | |
console.log('fib: ', `Result: ${fib(13)}`, ` - Loop count: ${i}`); | |
let a = 0; | |
function optimizeFib(num, cache = {}) { | |
if (cache[num]) { | |
return cache[num]; | |
} | |
if (num <= 1) { | |
return 1; | |
} | |
a++; | |
return cache[num] = optimizeFib(num - 1, cache) + optimizeFib(num - 2, cache); | |
} | |
console.log('optimizeFib: ', `Result: ${optimizeFib(13)}`, ` - Loop count: ${a}`); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment