I have to multiply the sign of all elements in an array.
For example 1:
JavaScript
x
4
1
input: [1, 2, 3]
2
output: 1
3
Explain: 1 * 1 * 1 = 1
4
Ex2:
JavaScript
1
4
1
input: [1, -2, 3]
2
output: -1
3
Explain: 1 * (-1) * 1 = -1
4
Ex3:
JavaScript
1
4
1
input: [1, -2, 3, 0]
2
output: 0
3
Explain: 1 * (-1) * 1 * 0 = 0
4
And here is my solution
JavaScript
1
5
1
function cal(A)
2
{
3
return A.reduce((total, currentValue) => total * Math.sign(currentValue), 1);
4
}
5
However, the output of ex3 cal([1, -2, 3, 0])
is -0
.
I’ve already thought about adding one more condition like this
JavaScript
1
9
1
function cal(A)
2
{
3
var total = A.reduce((total, currentValue) => total * Math.sign(currentValue), 1);
4
if(total === 0)
5
return 0;
6
else
7
return total;
8
}
9
And obviously, It looks ugly. Is there a more elegant way to resolve that?
Advertisement
Answer
In order to avoid conditional checks and keep the function purely computational you can use the curious rules of -0
to simply add 0 to the result of your reduce()
which will have no effect on non-zero results but will have the effect of converting -0
to 0
.
JavaScript
1
7
1
function cal(arr) {
2
return arr.reduce((a, c) => a * Math.sign(c), 1) + 0;
3
}
4
5
console.log(cal([1, 2, 3])); // 1
6
console.log(cal([1, -2, 3])); // -1
7
console.log(cal([1, -2, 3, 0])); // 0
See signed zero for more general discussion.