Skip to content

Commit f7fe8ad

Browse files
authored
refactor: Add TextUtil.pluralize (#2539)
We have 2 copies of `pluralize` in Enterprise and plugins. Adding it to `TextUtil` so it can be reused.
1 parent 006c29e commit f7fe8ad

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

packages/utils/src/TextUtils.test.ts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,3 +85,15 @@ describe('sort text', () => {
8585
expect(TextUtils.sort('A', 'A', false)).toBe(0);
8686
});
8787
});
88+
89+
describe('pluralize', () => {
90+
it('handles singular', () => {
91+
expect(TextUtils.pluralize(1, 'item')).toBe('item');
92+
expect(TextUtils.pluralize(1, 'item', 'pluralized')).toBe('item');
93+
});
94+
95+
it('handles plural', () => {
96+
expect(TextUtils.pluralize(2, 'item')).toBe('items');
97+
expect(TextUtils.pluralize(2, 'item', 'pluralized')).toBe('pluralized');
98+
});
99+
});

packages/utils/src/TextUtils.ts

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,24 @@ export class TextUtils {
6060
}
6161
return 0;
6262
}
63+
64+
/**
65+
* Pluralize a string based on a value
66+
* @param value The value to use for pluralization
67+
* @param singular The singular form of the string
68+
* @param pluralized The pluralized form of the string. If not provided, will append 's' to the singular form.
69+
* @returns The pluralized string
70+
*/
71+
static pluralize(
72+
value: number,
73+
singular: string,
74+
pluralized?: string
75+
): string {
76+
if (value === 1) {
77+
return singular;
78+
}
79+
return pluralized ?? `${singular}s`;
80+
}
6381
}
6482

6583
export default TextUtils;

0 commit comments

Comments
 (0)