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 >
_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.
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;
});
My suggestion meets these guidelines:
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§ion=2#High-level_languages
Most helpful comment
i think
-operator is what you said 馃槀