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