septs
1
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
ljharb
3
2 Likes