Home > front end >  The elegant way to resolve negative zero in Javascript
The elegant way to resolve negative zero in Javascript

Time:06-28

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?

CodePudding user response:

In your example, there is no need to multiply all the values. If there is at least one zero, the result is zero, so there is no need to iterate through the entire array. Example below:

function compute(arr)
{
    let result = true;
    for (let item of arr) {
        if (item === 0) return 0;
        if (item < 0) result = !result;
    }
    return result ? 1 : -1;
}

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

CodePudding user response:

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.

  • Related