Last active
October 18, 2022 13:33
-
-
Save Ynote/3ac587e2269c16dc50d758e9807b9c22 to your computer and use it in GitHub Desktop.
[Javascript] - Tail-recursive factorial function
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
// This is just a short reminder of this great explanation: | |
// http://www.2ality.com/2015/06/tail-call-optimization.html | |
// not TCO | |
function factorial(n) { | |
if (n <= 0) return 1; | |
return n * factorial(n-1); // here, the main recursive call not in a tail position because of the `n` context. | |
} | |
// TCO | |
function factorial(n) { | |
return recursiveFactorial(n, 1); | |
} | |
function recursiveFactorial(n, accumulator) { | |
if (n <= 0) return accumulator; | |
return recursiveFactorial(n-1, n*accumulator); | |
} |
I think you have a bug because of the missing
return
statement
@gibbok Thanks for your review! I missed that, it's fixed now :)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think you have a bug because of the missing
return
statement