Symbol.compareTo protocol

class Sample {
   constructor(value) {
      this.#internal = value
   }

   [Symbol.compareTo](b) { // returns `-1`, `0`, `1`
      if (input instanceof Sample) {
          return this.#internal < b.#internal ? 1 : -1
      }
      return -1
   }
}

const samples = [
    new Sample(2),
    new Sample(1),
]

samples.sort() // effect `Array.prototyp.sort` default behavior

References:

What would be the expected behavior when the array contains a mix of different types?

class Sample1 {
   [Symbol.compareTo](b) {
     console.log('sample1 comparator called');
     return this.toString().localeCompare(b.toString());
   }
}

class Sample2 {
   [Symbol.compareTo](b) {
      console.log('sample2 comparator called');
      return this.toString().localeCompare(b.toString());
   }
}

const samples = [
    new Sample1(),
    new Sample2(),
]

samples.sort();
// sample1 called or sample2, or both?
1 Like

This concept was proposed this year, and rejected, here:
https://github.com/tc39/notes/blob/827c5f98554b6e04d81c2c265f78f6f7ddf8415a/meetings/2020-06/june-4.md#generic-comparison

2 Likes