Skip to content

Instantly share code, notes, and snippets.

@Ynote
Last active October 18, 2022 13:33
Show Gist options
  • Save Ynote/3ac587e2269c16dc50d758e9807b9c22 to your computer and use it in GitHub Desktop.
Save Ynote/3ac587e2269c16dc50d758e9807b9c22 to your computer and use it in GitHub Desktop.
[Javascript] - Tail-recursive factorial function
// 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);
}
@twentyonepepes
Copy link

Legendary

@gibbok
Copy link

gibbok commented Sep 29, 2022

I think you have a bug because of the missing return statement

function factorial(n) {
  return recursiveFactorial(n, 1); // add return here
}

function recursiveFactorial(n, accumulator) {
  if (n <= 0) return accumulator;

  return recursiveFactorial(n-1, n*accumulator);
}

@Ynote
Copy link
Author

Ynote commented Oct 18, 2022

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