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
My two cents, with a function that returns the same results as Math.sign would do, ie sign(-0) --> -0, sign(-Infinity) --> -Infinity, sign(null) --> 0, sign(undefined) --> NaN, etc.
function sign(x) {
return +(x > -x) || (x && -1) || +x;
}
Jsperf won't let me create a test or revision, sorry for not being able to provide you with tests (i've given jsbench.github.io a try, but results seem much closer to one another than with Jsperf...)
If someone could please add it to a Jsperf revision, I would be curious to see how it compares to all the previously given solutions...
Thank you!
Jim.
EDIT:
I should have written:
function sign(x) {
return +(x > -x) || (+x && -1) || +x;
}
((+x && -1)
instead of (x && -1)
) in order to handle sign('abc')
properly (--> NaN)
I thought I'd add this just for fun:
function sgn(x){
return 2*(x>0)-1;
}
0 and NaN will return -1
works fine on +/-Infinity
Very similar to Martijn's answer is
function sgn(x) {
isNaN(x) ? NaN : (x === 0 ? x : (x < 0 ? -1 : 1));
}
I find it more readable. Also (or, depending on your point of view, however), it also groks things that can be interpreted as a number; e.g., it returns -1
when presented with '-5'
.