Skip to content

Instantly share code, notes, and snippets.

@pastleo
Last active March 11, 2020 17:20
Show Gist options
  • Save pastleo/be36fd0b2fe185d4b6ada7df508cba12 to your computer and use it in GitHub Desktop.
Save pastleo/be36fd0b2fe185d4b6ada7df508cba12 to your computer and use it in GitHub Desktop.
tail call optimization on fibonacci
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