Choosing a plural form
Intl.PluralRules
Chrome63
Edge18
Firefox58
Safari13
Features it needs
- Intl.PluralRulesWidely available
Picking between "1 file" and "2 files" by testing count === 1 is only correct in English, and barely. Russian needs one form for 3 and another for 5, and Polish and Arabic have more. Intl.PluralRules answers which category a number falls into for a locale, so the branching stops being a guess. It returns the category rather than the word, which is the part worth knowing before reaching for it.
When this applies
Choosing between singular and plural wording for a count.
The native approach
const pr = new Intl.PluralRules("en-US");
const forms = { one: "file", other: "files" };
`${count} ${forms[pr.select(count)]}`; // "1 file", "2 files"
// Ordinals are the same API with a different type.
new Intl.PluralRules("en-US", { type: "ordinal" }).select(22); // "two"When the dependency is still right
An answer that always says "the platform covers it" is worse than no answer. These are the cases where this one does not hold.
- You need the plural word itself. Intl.PluralRules returns a category such as "one" or "other" and never inflects anything, so "person" to "people" and "index" to "indices" still need pluralize or a table of your own. This is the difference that decides most cases.
- You pluralise arbitrary nouns you do not control, such as user-supplied or database-driven labels. A category is only useful when you already hold both forms, which you cannot if the noun is unknown at build time.
- You singularise as well as pluralise. pluralize goes both directions and this API goes neither.
- Your strings already run through an ICU message catalogue. It has plural selection built in and doing it twice is how the two disagree.
Signs it was hand-rolled
No package is involved in any of these, so nothing would match in a package.json. If the code looks like one of them, this rule applies anyway, and the conditions above still decide.
- a count === 1 ternary picking between two words, or a bare + "s" appended to a noun
- a lookup of irregular plurals kept next to the component that renders them