Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Ruby has something called a Combined Comparison or "Spaceship" Operator, it looks like this: <=>

It 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 end up with the same result?


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

It also does not work in Internet Explorer, Safari or all Mobile Browsers (see MDN)


@duques_l found a function here. It works very well, you can test it on JSFiddle

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

Update: @duques_l changed the function a bit and now it works fine (I think so anyway, 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;
    }
}

like image 812
Kaspar Lee Avatar asked Jan 18 '16 10:01

Kaspar Lee


People also ask

What is === operator in JavaScript?

The strict equality operator ( === ) checks whether its two operands are equal, returning a Boolean result. Unlike the equality operator, the strict equality operator always considers operands of different types to be different.

What is the spaceship operator?

In PHP 7, a new feature, spaceship operator has been introduced. It is used to compare two expressions. It returns -1, 0 or 1 when first expression is respectively less than, equal to, or greater than second expression.

How many comparison operators are there in JavaScript?

In JavaScript, there are two types of comparison operators: Type-converting (or Abstract) Strict.


2 Answers

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

Math.sign(a - b); 

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

like image 173
madox2 Avatar answered Sep 23 '22 20:09

madox2


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;
  }
}
like image 44
Léo Avatar answered Sep 20 '22 20:09

Léo