Skip to content

Instantly share code, notes, and snippets.

@thephilip
Created May 3, 2017 16:58
Show Gist options
  • Save thephilip/478583dbd20d9bbb808ee5201887660f to your computer and use it in GitHub Desktop.
Save thephilip/478583dbd20d9bbb808ee5201887660f to your computer and use it in GitHub Desktop.
// factorial (imperitive)
const factorial = n => {
let result = 1;
while (n > 1) {
result *=n;
n--;
}
return result;
};
// factorial (declarative)
const factorial = (n,accum=1) => {
if (n < 2) {
//return 1; // base case (prevents infinite loop)
return accum;
}
//return n * factorial(n - 1);
return factorial(n - 1, n * accum); // putting factorial() last in order of operations (tail-call)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment