I’m doing the factorialize algorithm challenge and I would really appreciate if someone with a greater knowledge than me would explain me what’s wrong in the thinking process of my code
Im following these steps to factorialize a number:
-
Create a function with a parameter (num).
-
I create an if statement to accomplish the next task: factorialize(0) should return 1. If (num === 0) {return 1;}
-
Create an array inside the function.
-
Create a loop to iterate through num-1 numbers and push them into the array. So we add the current number + all the previous values to the array. Example: If our number is 5 we add 5, 4, 3, 2, 1.
-
Use the reduce method into the array to multiply the values of each number in the array (factorialize).
-
Return the given value.
function factorialize(num) {
if (num === 0) { return 1; }
else {var array = [];
for(i = num; i >= 1; i--){
var newArray = array.push[i];
newArray.reduce(function(previousVal, currentVal){
return previousVal * currentVal;
});
}
}
}
factorialize(5);
I am mainly getting 2 douts now. This way to solve the algorithm might not be the most efficient one okay but:
-
Is this a viable way to solve it?
-
Why am I getting “cannot read property ‘reduce’ of undefined”.
Link to the challenge:
https://www.freecodecamp.org/challenges/factorialize-a-number