Typescript: Combined Comparison (Spaceship) Operator

Created on 29 May 2018  路  6Comments  路  Source: microsoft/TypeScript

Search Terms

  • Three-way comparison
  • spaceship operator
  • <=>

Suggestion

Add a new operator (expr) <=> (expr), it returns 0 if both operands are equal, 1 if the left is greater, and -1 if the right is greater. It uses exactly the same comparison rules as used by the existing comparison operators: <, <=, ==, >= and >

References

Use Cases

_What do you want to use this for?_ / _What shortcomings exist with current approaches?_
This removes much boilerplate code when writing sorting functions, although it could be useful in other instances as well.

Examples

Basic use case with current syntax:

data = data.sort((a, b) => {
    if (a.value > b.value) {
        return 1;
    } else if (a.value < b.value) {
        return -1;
    } else {
        return 0;
    }
});

new syntax:

data = data.sort((a, b) => {
    return a.value <=> b.value;
});

Checklist

My suggestion meets these guidelines:

  • [x] This wouldn't be a breaking change in existing TypeScript / JavaScript code
  • [x] This wouldn't change the runtime behavior of existing JavaScript code
  • [x] This could be implemented without emitting different JS based on the types of the expressions
  • [ ] This isn't a runtime feature (e.g. new expression-level syntax)
Out of Scope Suggestion

Most helpful comment

i think - operator is what you said 馃槀

data.sort((a, b) => a - b);

All 6 comments

i think - operator is what you said 馃槀

data.sort((a, b) => a - b);

In addition to that:

  • [x] This isn't a runtime feature (e.g. new expression-level syntax)

Yes it is.

@Kingwl @kpdonn Oh man, I didn't think of that, thanks for the pointer. ^^

The - operator does not work on strings, though, correct? If you are finding this and need to use it on strings, take a look at String.localeCompare().

Doesnt work on strings or arrays, also, the funciton does accept numbers lower than -1 and higher than 1 but this is not intended. So it's always better, to ensure full support in the future, to just use -1, 0 and 1.

Several languages have it. It's very useful to have a standard way to compare instances
https://en.wikipedia.org/w/index.php?title=Three-way_comparison&section=2#High-level_languages

Was this page helpful?
0 / 5 - 0 ratings

Related issues

bgrieder picture bgrieder  路  3Comments

dlaberge picture dlaberge  路  3Comments

siddjain picture siddjain  路  3Comments

uber5001 picture uber5001  路  3Comments

kyasbal-1994 picture kyasbal-1994  路  3Comments