pluralize function
Picks the singular or plural form of a word for a count. French takes the singular for 0 too: pass Math.abs(count) < 2 as isSingular.
ts
import { pluralize } from 'utils';Signature
ts
export function pluralize(
count: number,
singular: string,
plural = `${singular}s`,
isSingular = Math.abs(count) === 1,
): stringParameters
| Name | Description |
|---|---|
count | The number of items. |
singular | The singular form, such as 'alarm'. |
plural | The plural form. Defaults to singular followed by s. |
isSingular | Whether the count takes the singular. Defaults to Math.abs(count) === 1 (English). |
Returns
The form matching the count.
Example
ts
pluralize(3, 'alarm'); // 'alarms'
pluralize(0, 'alarme', 'alarmes', Math.abs(0) < 2); // 'alarme'Tests
Line coverage: 100 %.
- ✅ picks the form for 1
- ✅ picks the form for -1
- ✅ picks the form for 0
- ✅ picks the form for 3
- ✅ picks the form for 1.5
- ✅ uses the given plural and singular rule
- ✅ takes the defaults
Source
src/string/pluralize.ts (on GitHub)
Source code
ts
/**
* Picks the singular or plural form of a word for a count. French takes the singular for 0 too: pass
* `Math.abs(count) < 2` as `isSingular`.
*
* @param count - The number of items.
* @param singular - The singular form, such as `'alarm'`.
* @param plural - The plural form. Defaults to `singular` followed by `s`.
* @param isSingular - Whether the count takes the singular. Defaults to `Math.abs(count) === 1` (English).
* @returns The form matching the count.
* @example
* pluralize(3, 'alarm'); // 'alarms'
* pluralize(0, 'alarme', 'alarmes', Math.abs(0) < 2); // 'alarme'
*/
export function pluralize(
count: number,
singular: string,
plural = `${singular}s`,
isSingular = Math.abs(count) === 1,
): string {
return isSingular ? singular : plural;
}Test file
ts
import { pluralize } from './pluralize';
describe(pluralize, () => {
it.for([
[1, 'alarm'],
[-1, 'alarm'],
[0, 'alarms'],
[3, 'alarms'],
[1.5, 'alarms'],
] as const)('picks the form for %s', ([count, expected]) => {
expect(pluralize(count, 'alarm', 'alarms', Math.abs(count) === 1)).toBe(expected);
});
it('uses the given plural and singular rule', () => {
expect(pluralize(2, 'box', 'boxes', Math.abs(2) === 1)).toBe('boxes');
expect(pluralize(0, 'alarme', 'alarmes', true)).toBe('alarme');
});
it('takes the defaults', () => {
expect(pluralize(3, 'alarm')).toStrictEqual(pluralize(3, 'alarm', 'alarms', false));
});
});Keywords: pluralize, strings, function