Number.sign() in javascript

前端 未结 15 2350
日久生厌
日久生厌 2020-11-30 21:03

Wonder if there are any nontrivial ways of finding number\'s sign (signum function)?
May be shorter / faster / more elegant solutions than the obvious one



        
15条回答
  •  余生分开走
    2020-11-30 21:37

    Should this not support JavaScript’s (ECMAScript’s) signed zeroes? It seems to work when returning x rather than 0 in the “megafast” function:

    function sign(x) {
        return typeof x === 'number' ? x ? x < 0 ? -1 : 1 : x === x ? x : NaN : NaN;
    }
    

    This makes it compatible with a draft of ECMAScript’s Math.sign (MDN):

    Returns the sign of the x, indicating whether x is positive, negative or zero.

    • 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.

提交回复
热议问题