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:

JavaScript

Ex2:

JavaScript

Ex3:

JavaScript

And here is my solution

JavaScript

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

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

JavaScript

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

See signed zero for more general discussion.

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