Hi, could someone look at my code please. I can pass the test but i think my solution may be a bit messy. Could someone let me know please?
Also, am i missing something?, why return a 1 from 0. 1 is not the factor for 0, I asked google. this requirement is what is making the code look messy i think.
Cheers
Mark
function factorialize(num) {
var numbers = []; //empty array to fill
var high = num; //sets (num) as "high" number
var low = 0; //sets iteration stop
//if else fills challenge requirement of returning 1 from 0 only
if (num > 0)
//creates an array by iterating (num)
for (var i = high; i > low; i--){
numbers.push(i);
}
//multiply array items to get factor
factored = numbers.reduce(function(high, low) {
return low * high;
});
return factored;
}
else {
return 1;
}
}
factorialize(20);
Can you please take a look at my code? My logic is a bit similar to yours, but I count it up although you count down. Why doesnt this work? Is it because of i? But how? Thank you
function factorialize(num) {
if(num>0){
while(i<num-1){
product*=i;
i++;
}
console.log(product);
}
else {
return 1;
}
}
factorialize(5);
Your comments are exactly what I was looking for. I came to a similarly messy solution as OP, but I knew there was a better way, I just couldn’t put my finger on it. Thank you!
After doing some reading up on ES6, I managed to refactor my code using reduce and fill():
// create a new array with num items
return Array(num).fill()
// reduce the array starting from 1
.reduce((prev, curr, index) => prev + prev * index, 1);
}
factorialize(5);```
Thanks for the info.
This clears some things up and after I complete the basic JS algorithm challenges, I might go back to see if I can solve it with arrays, for the extra practice.
this is the route I took. I was initializing num to 1 though because of the wikipedia post on factorials so I was having some trouble at first, came to this post and seen this, almost an exact match. Except I was calling variable answer, X,
I originally tried solving the problem with recursion (even though we didn’t go over recursion in the lessons) but in the end I went with array.reduce method.