Created
November 5, 2025 22:35
-
-
Save jossmac/8449f7a7499de77f735dd6979434ae94 to your computer and use it in GitHub Desktop.
Returns the count and appropriate plural or singular form of a term.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * Returns the count and appropriate plural or singular form of a term. | |
| * | |
| * @example | |
| * pluralize(0, 'wallet'); // '0 wallets' | |
| * pluralize(1, 'wallet'); // '1 wallet' | |
| * pluralize(2, 'wallet'); // '2 wallets' | |
| * pluralize(1, ['person', 'people']); // '1 person' | |
| * pluralize(2, ['person', 'people']); // '2 people' | |
| * pluralize(1, ['person', 'people'], false); // 'person' | |
| * pluralize(2, ['person', 'people'], false); // 'people' | |
| * | |
| * @param count - The number of items. | |
| * @param terms - The singular, and optionally plural, forms of the term. | |
| * @param includeCount - Whether to include the count in the result. Defaults to `true`. | |
| * @returns The appropriate plural or singular form of the given term(s), prefixed with the count if `includeCount` is true. | |
| */ | |
| export function pluralize( | |
| count: number, | |
| terms: string | [singular: string, plural: string], | |
| includeCount = true | |
| ) { | |
| const [singular, plural] = Array.isArray(terms) | |
| ? terms | |
| : commonEnglishPlural(terms); | |
| const term = count === 1 ? singular : plural; | |
| if (includeCount) { | |
| return `${count} ${term}`; | |
| } | |
| return term; | |
| } | |
| /** | |
| * Don't make consumers provide both terms for common English plural cases, | |
| * e.g. wallet → wallets, address → addresses | |
| */ | |
| function commonEnglishPlural(term: string): [singular: string, plural: string] { | |
| if (term.endsWith('s')) { | |
| return [term, `${term}es`]; | |
| } | |
| return [term, `${term}s`]; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment