Pick plural forms with Intl.PluralRules
Pick singular and plural forms with Intl.PluralRules, and build ordinals like 1st, 2nd and 3rd from the ordinal type. Node.js 18 and later.
n === 1 ? 'file' : 'files' works in English and fails in Russian, Arabic and every language with more than two forms. Intl.PluralRules returns the category the language actually uses, on Node.js 18 and later.
const cardinal = new Intl.PluralRules('en-US');
const ordinal = new Intl.PluralRules('en-US', { type: 'ordinal' });
const files = (n) => `${n} file${cardinal.select(n) === 'one' ? '' : 's'}`;
console.log(files(1), files(0), files(2));
const suffix = { one: 'st', two: 'nd', few: 'rd', other: 'th' };
console.log([1, 2, 3, 4, 11, 12, 13, 21, 22, 101].map((n) => n + suffix[ordinal.select(n)]));
console.log(new Intl.PluralRules('ar').select(2), new Intl.PluralRules('ru').select(3));1 file 0 files 2 files
[
'1st', '2nd',
'3rd', '4th',
'11th', '12th',
'13th', '21st',
'22nd', '101st'
]
two fewselect(n) returns a string such as one or other and you map it to your own words. In English the cardinal categories are one and other, so 0 files and 2 files share a form. The ordinal type gives one, two, few and other, which the example maps to st, nd, rd and th, and handles 11th, 12th and 13th correctly, where a naive last-digit rule fails. Russian and Arabic return more categories, as the last line shows for 3 in Russian (few) and 2 in Arabic (two). The categories are defined by CLDR and exposed by ECMA-402 Intl.PluralRules.
The method returns only a category. You still need a translated string for each one, and Intl.NumberFormat for the number.