'Why always return "None" string, like my if statment was always false?
My second approach to learning JS.
Maybe someone will tell me why I always get "none".
Thank you for any help.
const reverseFactorial = (num) => {
for (let i = 1; num > 1; num = num / ++i) {
if (num === 1) return `${i}`
}
return 'None'
};
console.log(reverseFactorial(120))
Solution 1:[1]
Sure it is possible to perform this also with the ternary operator, you have to change the internal 'if' check with an assignment to a temporary variable (let's call it 'result') which will be holding the temporary result at each iteration until the num equals one (num === 1) condition is met or num is no longer greater than nor equal to one (num >= 1); at that point, the for loop will end and the result is returned with the associated 'reversefactorial' value or 'None' value:
const reverseFactorial = (num) => {
// this avoids exceptions if num < 1 as you always return a valid value
// by returning zero, the function is reporting an invalid num argument
result = 0
for (let i = 1; num >= 1; num = num / ++i) { // condition updated to "num >= 1"
result = (num === 1) ? `${i}` : 'None'
}
return result
};
console.log('reverseFactorial(120) gives: ', reverseFactorial(120))
You can also speed the loop by taking everything out like this:
const reverseFactorial = (num) => {
// take into account num < 1
if (num < 1) {
i = 0;
num = 1;
}
else i = 1;
for (;num >= 1; num = num / ++i) { // condition updated to "num >= 1"
if (num === 1) break;
}
return (num === 1) ? `${i}` : 'None'
};
console.log('reverseFactorial(120) gives: ', reverseFactorial(120))
Though, as you can see, it is now more cumbersome to take into account invalid num entries with the starting if to correctly set the initial value for i; anyway this function should be faster than the previous one, the more the higher num is as we are taking the assigment out of the loop.
Solution 2:[2]
check your if condition and for loop condition.num>i is your for loop condition so when i=1 in for loop it will immediately exit the for loop and not enters into the if condition so your if condition is never satisfied that's why you always get none.
so change your for loop condition to
num>=1;
Here's a working demo
Code Snippet
const reverseFactorial = (num) => {
for (let i = 1; num >= 1; num = num / ++i) { // condition updated to "num >= 1"
if (num === 1) return `${i}`
}
return 'None'
};
console.log('reverseFactorial(120) gives: ', reverseFactorial(120))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | jsN00b |
