PHP, Ruby, Groovy have spaceship operator `<=>`. In short, this operator 
compares values and returns `1`, `-1`, `0`.

ECMAScript spec's `TypedArray#sort` has the default comparison part like 
following code, so I think it's useful that appending spaceship operator to 
ECMAScript like it.
http://www.ecma-international.org/ecma-262/8.0/#sec-%typedarray%.prototype.sort

```javascript
function isPlusZero(val) {
    return val === 0 && 1 / val === Infinity;
}

function defaultCompare(x, y) {
    const [isNaN_x, isNaN_y] = [Number.isNaN(x), Number.isNaN(y)];

    if(isNaN_x && isNaN_y)
        return 0;

    if(isNaN_x)
        return 1;

    if(isNaN_y)
        return -1;

    if(x < y)
        return -1;

    if(x > y)
        return 1;

    if(x === 0 && y === 0) {
        const [isPlusZero_x, isPlusZero_y] = [isPlusZero(x), isPlusZero(y)];

        if(!isPlusZero_x && isPlusZero_y)
            return -1;

        if(isPlusZero_x && !isPlusZero_y)
            return 1;
    }

    return 0;
}
```

```javascript
// NaN behave like the biggest number
NaN <=> NaN // 0
NaN <=> 42 // 1
42 <=> NaN // -1
Infinity <=> NaN // -1

// finite
10 <=> 10 // 0
-1 <=> 10 // -1
10 <=> -1 // 1

// 0, -0 are not the same
-0 <=> 0 // -1
0 <=> -0 // 1
```

## Use cases

```javascript
// Array#sort can use TypedArray#sort default comparison part
[10, 5, NaN, -1].sort((a, b) => a <=> b); // [-1, 5, 10, NaN]

// desc order
new Float64Array([10, 5, NaN, -1]).sort((a, b) => -(a <=> b)); // [NaN, 10, 5, 
-1]
```

## Problems

`TypedArray#sort` default comparison part has no `string` order function.

```javascript
"abc" <=> "def" // same as "abc".localeCompare("def") ?
"abc" <=> 42 // same as "abc".localeCompare("42") ?
```

I found the reference to spaceship operator in ES Discuss. It has Already 
discussed in TC39 meeting?
https://esdiscuss.org/topic/informative-notes#content-3
_______________________________________________
es-discuss mailing list
[email protected]
https://mail.mozilla.org/listinfo/es-discuss

Reply via email to