Combined Comparison / Spaceship Operator (<=>) in Javascript?

In Ruby there is an operator called "Combined Comparison" or "Spaceship", it looks like this: <=>

This does the following:

 a <=> b := if a < b then return -1 if a = b then return 0 if a > b then return 1 

credit

Is there a similar operator in Javascript? If not, how can I get the same result?


@ madox2 suggested using Math.sign(a - b) , which works for numbers, but not for arrays (to compare arrays you need to use array.length ).

It also does not work in Internet Explorer, Safari, or in all mobile browsers (see MDN ).


@duques_l found the function here . This works very well, you can check it out on JSFiddle

The only problem is that if the strings are not comparable, the function returns -1 instead of nil

Update: @duques_l slightly changed the function, and now it works fine (I think so, here is the JSFiddle ):

 function spaceship(val1, val2) { if ((val1 === null || val2 === null) || (typeof val1 != typeof val2)) { return null; } if (typeof val1 === 'string') { return (val1).localeCompare(val2); } else { if (val1 > val2) { return 1 } else if (val1 < val2) { return -1 } return 0; } } 

+13
source share
2 answers

As far as I know, there is no such operator in JavaScript, but you can use the Math.sign () function :

 Math.sign(a - b); 

NOTE. As mentioned in the comments, Math.sign () is currently not supported by all browsers. Check for compatibility ( MDN ).

+13
source

from: http://sabrelabs.com/post/48201437312/javascript-spaceship-operator

improved version:

 function spaceship(val1, val2) { if ((val1 === null || val2 === null) || (typeof val1 != typeof val2)) { return null; } if (typeof val1 === 'string') { return (val1).localeCompare(val2); } else { if (val1 > val2) { return 1; } else if (val1 < val2) { return -1; } return 0; } } 
+8
source

Source: https://habr.com/ru/post/1240843/


All Articles