Skip to content

Instantly share code, notes, and snippets.

@tomsaleeba
Created May 30, 2020 04:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomsaleeba/9d41c3b63085bee74426288b2ef5d692 to your computer and use it in GitHub Desktop.
Save tomsaleeba/9d41c3b63085bee74426288b2ef5d692 to your computer and use it in GitHub Desktop.
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