Factorialize a Number - How can I do this using reduce()?

Factorialize a Number - How can I do this using reduce()?
0

#1

Tell us what’s happening:
How can I do this using reduce()?
If I can use the for loop and decrement the num till it is === to 1 and assign it to an array then use reduce() will it work?
I can’t do it so I’m asking to show me the code if it can be done.

``````function factorialize(num) {
if(num === 0 || num === 1){
return 1;
}

for(var i = num-1; i >= 1; i-- ){
num*=i;
}

return num;
}

factorialize(5);
``````

Your Browser User Agent is: `Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:59.0) Gecko/20100101 Firefox/59.0`.

https://www.freecodecamp.org/challenges/factorialize-a-number

#2

Here’s two approaches using reduce.

``````function factorialize(num) {
var arr = []

while(num > 0) {
arr.push(num--)
}

return arr.reduce((accumulator, current) => {
return accumulator * current;
});
}
``````
``````function factorialize(num) {
return Array.apply(null, Array(num)).map((current, index) => {
return index + 1;
}).reduce((accumulator, current) => {
return accumulator * current;
});
}
``````

#3

Both of the above solutions fail for factorialize(0).

``````const factorialize = n => n === 0 ? 1 : Array.from(new Array(n),(_,idx) => idx+1)
.reduce((prod, val) => prod*val);
``````