Last active
March 11, 2020 17:20
-
-
Save pastleo/be36fd0b2fe185d4b6ada7df508cba12 to your computer and use it in GitHub Desktop.
tail call optimization on fibonacci
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
const fib = n => (n <= 2 ? 1 : fib(n - 1) + fib(n - 2)); | |
const fibTco = (n, a = 1, b = 1) => (n === 1 ? a : fibTco(n - 1, b, a+b)); | |
const nth = 42; | |
console.log(`fib(${nth}) =`); | |
console.log(` ${fib(nth)}`); | |
console.log(`fibTco(${nth}) = `); | |
console.log(` ${fibTco(nth)}`); | |
const tail = (n, a = 1) => { | |
if (n <= 1) { | |
return a; | |
} else { | |
return tail(n - 1, a + 1); | |
} | |
} | |
console.log('But js does not have tail call optimization?') | |
console.log('tail(10000) = ') | |
console.log(tail(10000)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment