Question

For a scrolling feature I use some Math-functions:

transform: "rotateY("+(Math.sign(this._backlog)*Math.sqrt(Math.abs(this._backlog)))+"deg)"

While this works well in Firefox, it doesn't work in Chrome with following message:

Uncaught TypeError: Object #<Object> has no method 'sign' 

Math.abs and Math.sqrt are working.

Which function I can use in Chrome?

Was it helpful?

Solution

Math.sign is only part of the draft specification for ES6 (§20.2.2.28), which is incomplete. Support for as-yet-unspecified features is likely to be spotty from engine to engine.

MDN previously claimed that Chrome 32 supported this, but as far as I can tell that was simply wrong. My version of Chrome (36) does not support it, and MDN now claims that only FireFox supports this function: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign.

But this is a pretty easy function to write yourself:

function sign(x){
    if( +x === x ) { // check if a number was given
        return (x === 0) ? x : (x > 0) ? 1 : -1;
    }
    return NaN;
}

NaN, +/-Infinity and -0 are handled correctly (sign(-0)==-0, sign(NaN)==NaN), and non-numeric inputs will return NaN. If you don't care about non-numeric inputs you can use this simplified one-liner (which still handles NaN, +/-Infinity and -0 but does not check the input type):

function sign(x){return x>0?1:x<0?-1:x;}

OTHER TIPS

The one line function:

var sign = function(n) {return n>0?1:n=0?0:-1;}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top