Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Tail resursion in JS
// the non-tail-recursive way
;(() => {
function fac(n) {
if (n === 1) {
return 1
}
const nextFac = fac(n - 1)
return n * nextFac // last thing we do it multiply
}
const start = Date.now()
console.log(`factorial of 5=${fac(5)}`)
console.log(`factorial of 24=${fac(24)}`)
console.log(Date.now() - start)
})()
// tail-recursive
;(() => {
function fac(n) {
if (n === 1) {
return 1
}
return go(n, n - 1)
}
function go(accum, n) {
const newAccum = accum * n
if (n === 1) {
return newAccum
}
return go(newAccum, n - 1) // last thing we do is recurse
}
const start = Date.now()
console.log(`factorial of 5=${fac(5)}`)
console.log(`factorial of 24=${fac(24)}`)
console.log(Date.now() - start)
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment