Skip to content
Advertisement

The elegant way to resolve negative zero in Javascript

I have to multiply the sign of all elements in an array.

For example 1:

input: [1, 2, 3]
output: 1
Explain: 1 * 1 * 1 = 1

Ex2:

input: [1, -2, 3]
output: -1
Explain: 1 * (-1) * 1 = -1

Ex3:

input: [1, -2, 3, 0]
output: 0
Explain: 1 * (-1) * 1 * 0 = 0

And here is my solution

function cal(A)
{
    return A.reduce((total, currentValue) => total * Math.sign(currentValue), 1);
}

However, the output of ex3 cal([1, -2, 3, 0]) is -0.

I’ve already thought about adding one more condition like this

function cal(A)
{
    var total = A.reduce((total, currentValue) => total * Math.sign(currentValue), 1);
    if(total === 0)
        return 0;
    else
        return total;
}

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.

function cal(arr) {
  return arr.reduce((a, c) => a * Math.sign(c), 1) + 0;
}

console.log(cal([1, 2, 3]));     // 1
console.log(cal([1, -2, 3]));    // -1
console.log(cal([1, -2, 3, 0])); // 0

See signed zero for more general discussion.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement