Created
May 30, 2020 04:29
-
-
Save tomsaleeba/9d41c3b63085bee74426288b2ef5d692 to your computer and use it in GitHub Desktop.
Tail resursion in JS
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
// 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