Skip to content

Instantly share code, notes, and snippets.

@ahsquared
Created April 16, 2014 13:59
Show Gist options
  • Save ahsquared/10880037 to your computer and use it in GitHub Desktop.
Save ahsquared/10880037 to your computer and use it in GitHub Desktop.
Sign of a number in Javascript
From http://stackoverflow.com/questions/7624920/number-sign-in-javascript
Short excerpt
Use this and you'll be safe and fast
function sign(x) {
return typeof x === 'number' ? x ? x < 0 ? -1 : 1 : x === x ? 0 : NaN : NaN;
}
1. Obvious and fast
function sign(x) { return x > 0 ? 1 : x < 0 ? -1 : 0; }
1.1. Modification from kbec - one type cast less, more performant, shorter [fastest]
function sign(x) { return x ? x < 0 ? -1 : 1 : 0; }
caution: sign("0") -> 1
2. Elegant, short, not so fast [slowest]
function sign(x) { return x && x / Math.abs(x); }
caution: sign(+-Infinity) -> NaN, sign("0") -> NaN
As of Infinity is a legal number in JS this solution doesn't seem fully correct.
3. The art... but very slow [slowest]
function sign(x) { return (x > 0) - (x < 0); }
4. Using bit-shift
fast, but sign(-Infinity) -> 0
function sign(x) { return (x >> 31) + (x > 0 ? 1 : 0); }
5. Type-safe [megafast]
! Seems like browsers (especially chrome's v8) make some magic optimizations and this solution turns out to be much more performant than others, even than (1.1) despite it contains 2 extra operations and logically never can't be faster.
function sign(x) {
return typeof x === 'number' ? x ? x < 0 ? -1 : 1 : x === x ? 0 : NaN : NaN;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment