Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom Intl.Collators?

Is it possible to create a custom Intl.Collator object for Javascript? Suppose I have:

var letters = [ "a", "n", "ñ", "x" ]

If I sort them, the ñ will go to the end by default:

letters.sort() // [ "a", "n", "x", "ñ" ]

However, using the new Intl.Collator, I can do:

letters.sort(Intl.Collator('es').compare)

Which sorts by Spanish (es) rules, and puts the ñ after n.

[ "a", "n", "ñ", "x" ] 

Now, suppose for some reason I wanted to write a Collator of my own, that would put the ñ first?

[ "ñ", "a", "n", "x" ] 

I haven’t been able to find any information about customizing a new rule set for Intl.Collator.

Is this possible?

Update

Yes, it is possible.

Update:

I have found advice in the ECMAscript i18n standard2 on how to create custom locales:

function MyCollator​(locales, options) {
  Intl​.Collator​.call​(this, locales, options);
  // initialize MyCollator properties
}
MyCollator​.prototype = Object​.create​(Intl​.Collator​.prototype);
MyCollator​.prototype​.constructor = MyCollator;
// add methods to MyCollator​.prototype
var collator = new MyCollator​("de-u-co-phonebk");
a​.sort​(collator​.compare);

1 Answers

You may be able to get what you want by using the "sensitivity" option.

The Intl.Collator.prototype is not writable.

You may be able to create and array with sort and character to set you own sort order.

$convert[character]= sortOrder ;

Array structure would depend on purpose.
With this structure you'd have to convert the result back again.

$letters = [$convert[a],$convert[n],$convert[ñ],$convert[x]);

This one would probably work best in most cases.

$letters = [[$convert[a],a],[$convert[n],n],[$convert[ñ],[ñ],[$convert[x],x]);
like image 99
Misunderstood Avatar answered Mar 16 '26 13:03

Misunderstood



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!