### Efficient Math.sign(value) polyfill

Posted:

**Sat Sep 12, 2020 9:23 am**Andrew, all,

stepping trough a lot of code these days ...

I pass this polyfill hundred and more times a day.
It is a three / four step process that returns (NaN / -1 / -0 / 0 / 1) as the sign of a value.

Better seen when you write it as this:
The 'if' line seems not to end in a ';' but a '}' is fine too.

Out of the blue I would write that as:
But I can be O so wrong.

I came across this single step solution:
I can't even start to imagine how many signs QCAD evaluates ...

For me it seems free to use and one can find it on many public places.

With or without the reference I include.

Regards,

CVH

stepping trough a lot of code these days ...

I pass this polyfill hundred and more times a day.

Code: Select all

```
// In input.js:
sign = Math.sign = function(x) { x = +x; if (x === 0 || isNaN(x)) { return Number(x); } return x > 0 ? 1 : -1; };
```

Better seen when you write it as this:

Code: Select all

```
sign = Math.sign = function(x) {
x = +x;
if (x === 0 || isNaN(x)) { return Number(x); }
return x > 0 ? 1 : -1;
};
```

Out of the blue I would write that as:

Code: Select all

```
sign = Math.sign = function(x) { x = +x; if (x === 0 || isNaN(x)) return Number(x); return x > 0 ? 1 : -1; };
// OR
sign = Math.sign = function(x) {
x = +x;
if (x === 0 || isNaN(x)) return Number(x);
return x > 0 ? 1 : -1;
};
```

I came across this single step solution:

Code: Select all

```
// Efficient Polyfill Math.sign:
// Copy from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign
// If x is NaN, the result is NaN.
// If x is -0, the result is -0.
// If x is +0, the result is +0.
// If x is negative and not -0, the result is -1.
// If x is positive and not +0, the result is +1.
//
Math.sign = function(x) { return ((x > 0) - (x < 0)) || +x };
// A more aesthetic pseudo-representation:
// ( (x > 0) ? 1 : 0 ) // if x is positive, then positive one
// + // else (because you can't be both - and +)
// ( (x < 0) ? -1 : 0 ) // if x is negative, then negative one
// || // if x is 0, -0, or NaN, or not a number,
// +x // then the result will be x, (or) if x is
// // not a number, then x converts to number
// No extra type-coercing is needed to make (x > 0) or (x < 0) numbers because
// subtracting them from each other forces a type conversion from booleans to numbers.
```

For me it seems free to use and one can find it on many public places.

With or without the reference I include.

Regards,

CVH