Editing Signum Function (all) This edit will create a new revision. Your details (optional) Name Email (won’t be displayed; might be used for Gravatar) URL Test case details Title * Published (uncheck if you want to fiddle around before making the page public) Description (in case you feel further explanation is needed)(Markdown syntax is allowed) Derived from this question on StackOverflow: **[Number.sign() in JavaScript](http://stackoverflow.com/questions/7624920/number-sign-in-javascript)** Versions of the test: **test everything** — [only numbers](http://jsperf.com/signs-number) — [only integers](http://jsperf.com/signs-integer) Which approach do you think is the best? Vote on the answers! Are you a spammer? (just answer the question) Preparation code Preparation code HTML (this will be inserted in the <body> of a valid HTML5 document in standards mode) (useful when testing DOM operations or including libraries) Include JavaScript libraries as follows: <script src="//cdn.ext/library.js"></script> Define setup for all tests (variables, functions, arrays or other objects that will be used in the tests) (runs before each clocked test loop, outside of the timed code region) (e.g. define local test variables, reset global variables, clear canvas, etc.) (see FAQ) // OUR TEST CODE (see other versions) function test(sign) { sign(1) // +1 sign(1908235) // +1 sign(-.1e-1) // -1 sign(Math.random()*2-1) // ?? sign(0) // 0 sign(0.00000) // 0 sign(+Infinity) // +1 sign(-Infinity) // -1 sign(NaN) // 0 or NaN // other types sign("0") sign("") sign([]) sign("+23") sign(null) sign(undefined) } // 1. Obvious and fast function sign1 (x) { return x > 0 ? 1 : x < 0 ? -1 : 0; } // 1.1 Modification from kbec - one type cast less, more performant, shorter function sign1b(x) { return x ? x < 0 ? -1 : 1 : 0; } // 2. Elegant, short, not so fast function sign2 (x) { return x && x / Math.abs(x); } // (some issues with several cases, see answer.) // 3. The art... but very slow function sign3 (x) { return (x > 0) - (x < 0); } // 4. Type-safe: function sign4 (x) { return typeof x == 'number' ? x ? x < 0 ? -1 : 1 : isNaN(x) ? NaN : 0 : NaN; } Define teardown for all tests (runs after each clocked test loop, outside of the timed code region) (see FAQ) Code snippets to compare Test 1 Title Async (check if this is an asynchronous test) Code test(sign1) Test 2 Title Async (check if this is an asynchronous test) Code test(sign1b) Test 3 Title Async (check if this is an asynchronous test) Code test(sign2) Test 4 Title Async (check if this is an asynchronous test) Code test(sign3) Test 5 Title Async (check if this is an asynchronous test) Code test(sign4)