Another solution for the Javascript challenge: Factorialize a Number [SPOILERS]

Hello,

I solved this challenge last night, but then I wondered if it could be solved differently. Here it is:

Factorialize a Number
Return the factorial of the provided integer.

If the integer is represented with the letter n, a factorial is the product of all positive integers less than or equal to n.

Factorials are often represented with the shorthand notation n!

For example: 5! = 1 * 2 * 3 * 4 * 5 = 120

Remember to use Read-Search-Ask if you get stuck. Write your own code.

And here it is my first (and successful) solution:

function factorialize(num) {
  //create an array 
  var array = [];
  //The array must contain every number from 1 to num
  if (num > 0) {
  for(i=1; i<=num; i++) {
    array.push(i);
  }

   // if num = 0, return 1 
  } else {
    return 1;
  }
  
  //Reduction of the array
  return array.reduce(function (a,b) {
    return a * b;
  });
}  

factorialize(5);

Later, I wondered if that function could be composed by 2 smaller functions: the first could push the numbers into the array and the second would reduce it. Here is the code I tried:

    function factorialize(num) {
  //create an array 
  var array = [];

  //The array must contain every number from 1 to num
 function arrayCreation() {
  if (num > 0) {
  for(i=1; i<=num; i++) {
    array.push(i);
  }

   // if num = 0, return 1 
  } else {
    return 1;
  }
  }

  //Reduction of the array
  function reductionArray() {
  return array.reduce(function (a,b) {
    return a * b;
  });
    }
 arrayCreation();
 reductionArray();
}
factorialize(5);

However, when I test the code, the result is undefined. I don’t know if it’s a problem caused by the arguments of each function or by the scope of the variable array. Any thoughts?

Thanks in advance for your help

Your factorialize is not returning anything.

Replace the following line

  reductionArray();

with

return reductionArray();

While it is good that you have learned how to use the higher order function reduce to solve this problem, it can be solved without using an array, which will use less memory for large factorial numbers. Plus, creating the array and then “reducing” over it to create the result is double to iterations to solve the problem. Maybe your first solution did not use reduce and you were just testing alternate solutions. If so, then ignore my comments. Your code has O(n) memory complexity vs O(1) which is possible without using the array.

@gunhoo93, it was right under my nose…

@rmdawson71 Actually, the solution I showed before was the solution I gave to the challenge. I didn’t even think that the problem could be solved without an array. I will give it a try.

Thank you both for your help