I have the following example:
class MyClass {
constructor(name) {
this.name = name;
}
toString() {
return this.name;
}
valueOf() {
return this.name;
}
}
const list = [new MyClass("b"), new MyClass("ä")];
list.sort();
console.log(list.join());
list.sort(new Intl.Collator('de').compare);
console.log(list.join());
Here, the Collator
is required to get the correct sort order, but I want to get rid of it and I want to be able to compare instances of MyClass
with a simple myClass1 < myClass2
. This should theoretically be possible by changing the valueOf
function.
My question now is, is there any JavaScript built-in way to get a "locale" value of a string (similar to Intl.Collator
or localeCompare
) that I can return in my valueOf
function to get the order right?
No, there is no such info. Basically, unless you use Intl with specified locale directly (as with Intl.Collator
) or indirectly (as with localeCompare
), you will compare codepoints based on browser implementation of strings which is, most likely, by UTF-16 code points.