Build an ordinal indicator function with the JavaScript PluralRules API
I stumbled on the JavaScript Plural Rules API. Given a number, it will return the relevant plural rule for a locale. Here is an example in code:
const pr = new Intl.PluralRules('en-US', { type: "ordinal" });
pr.select(1); // one
pr.select(22); // two
But what does that mean?
Unicode, Languages
Languages handle pluralization differently. Unicode documents plural rules for many languages. According to that documentation, English has four rules for ordinals. Those rules correspond to the ordinal indicators: st, nd, rd, and th.
Putting it to use
Knowing that we can get the rule for a given number, and knowing that we can map those rules to indicators, let's write a function to return the ordinal indicator for any number.
function getOrdinalIndicator(num) {
if (typeof number !== "number") {
throw Error("Must pass a number")
}
const pr = new Intl.PluralRules('en-US', { type: "ordinal" });
const ordinalTypeMap = {
"one": "st",
"two": "nd",
"few": "rd",
"other": "th"
}
return ordinalTypeMap[pr.select(num)];
}
This is perhaps a silly use case for a useful API. See what else you can build with it!