Pluralize Counts With Intl.PluralRules

Choose singular or plural forms by CLDR plural category, including custom two and few forms for non-English locales.

JavascriptData Integrity

Code

javascriptsnippet
19 lines
export function pluralize(count, singular, plural, locale = "en") {
  if (typeof count !== "number" || !Number.isFinite(count)) {
    throw new TypeError("count must be a finite number");
  }
  const rules = new Intl.PluralRules(locale);
  const category = rules.select(count);
  const forms = typeof plural === "string"
    ? { one: singular, other: plural }
    : { one: singular, other: singular, ...plural };
  const word = forms[category] ?? forms.other ?? singular;
  return String(count) + " " + word;
}

export function pluralizeWithNumber(count, singular, plural, locale = "en") {
  const formatted = new Intl.NumberFormat(locale).format(count);
  const text = pluralize(count, singular, plural, locale);
  const separator = text.indexOf(" ");
  return separator === -1 ? text : formatted + text.slice(separator);
}

Inside the snippet

Pluralize Counts With Intl.PluralRules keeps everything in the functions pluralize and pluralizeWithNumber.

Invalid states are rejected up front: it throws TypeError instead of continuing with bad data.

Using it

The main signature reads export function pluralize(count, singular, plural, locale = "en")

Treat pluralize as the API: import it, and ignore the supporting code.

Key statements

return separator === -1 ? text : formatted + text.slice(separator);
const formatted = new Intl.NumberFormat(locale).format(count);
const word = forms[category] ?? forms.other ?? singular;

Interactive Tools for This Topic

FAQ

How are precondition violations signaled?
`TypeError` is raised at the guard, so invalid state never reaches the main logic.
What has to be installed first?
Nothing — the runtime itself provides everything the code touches. The file defines `pluralize`, `pluralizeWithNumber` at load time.