Learn TDD with Mocha: Factorial Feature - better way to do factorial than a for loop?

Hi y’all,
On the Learn TDD with Mocha: Factorial Feature (https://www.codecademy.com/paths/full-stack-engineer-career-path/tracks/fscp-test-driven-development-with-javascript/modules/fecp-learn-tdd-with-mocha/projects/factorial) project, task 6 says as follows:

Refactor your implementation code so that it is more concise and efficient. This could include cleaning up the existing code, or using a built-in method instead of a for loop for calculating the factorial of any input.

I was wondering what might be meant by using a built-in method there? I had a look with Google and can’t find anything that’s really more concise than a for loop—someone somewhere suggested a while loop, but you end up with more lines of code once you’ve declared the relevant variables. Any thoughts? My final code is below:

const Calculate = {
  factorial(input){
    if (input <= 1){
      return 1;
    };
    
    let currentSum = input;

    for (let i = input-1; i > 1; i--){
      currentSum *= i;
    };

    return currentSum;
  }
};

Not sure why they worded it like that exactly, but my guess is they are referring to recursion so there isn’t a loop. Switching from for to a while is possible, but that doesn’t feel any cleaner to me.

Refactoring it to be recursive would make it more concise. It isn’t required to pass this step though.

They may have just been trying to give general advice towards the refactor step even though they specified the possibility of using a ‘built-in’ method to calculate the factorial.

1 Like

Mainly answering for anyone else that stumbles upon this thread…! Thanks so much for your reply, making it recursive was a really good suggestion that I basically pretended to understand and then had to go and look up. And looking it up was fruitful, resulting in this code:

const Calculate = {
  factorial(input){
    
    return (input <= 1) ? 1: input * this.factorial(input-1);
  }

};

which I think is the most beautiful code I’ve written to date. Hooray!

1 Like