-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpluralize.ts
More file actions
202 lines (177 loc) · 6.43 KB
/
pluralize.ts
File metadata and controls
202 lines (177 loc) · 6.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
/**
* Pluralization utilities with PostGraphile-compatible Latin suffix handling
*
* Uses the 'inflection' package with custom overrides for Latin plural suffixes
* that PostGraphile handles differently than standard English pluralization.
*/
import * as inflection from 'inflection';
/**
* Latin plural suffixes that inflection handles differently than PostGraphile.
*
* The inflection library correctly singularizes Latin words (schemata -> schematum),
* but PostGraphile uses English-style naming (schemata -> schema).
*
* Format: [pluralSuffix, singularSuffix]
*/
const LATIN_SUFFIX_OVERRIDES: Array<[string, string]> = [
['schemata', 'schema'],
['criteria', 'criterion'],
['phenomena', 'phenomenon'],
['media', 'medium'],
['memoranda', 'memorandum'],
['strata', 'stratum'],
['curricula', 'curriculum'],
['data', 'datum'],
];
/**
* Compound words ending in "base" that the inflection library incorrectly
* singularizes via its (b)a branch in the ses$ rule (e.g. codebases -> codebasis).
* We intercept these before delegating to inflection.singularize().
*/
const COMPOUND_BASE_REGEX = /(database|codebase|firebase|knowledgebase)s$/i;
const TRAILING_TRIPLE_S_REGEX = /[sS]{3,}$/;
const TRAILING_TRIPLE_S_BEFORE_ES_REGEX = /[sS]{3,}(?=e[sS]$)/;
function normalizeTrailingSRun(suffix: string): string {
return suffix === suffix.toUpperCase() ? 'SS' : 'ss';
}
function normalizeTripleSBeforeEs(word: string): string {
return word.replace(TRAILING_TRIPLE_S_BEFORE_ES_REGEX, normalizeTrailingSRun);
}
function normalizeTrailingTripleS(word: string): string {
const match = word.match(TRAILING_TRIPLE_S_REGEX);
if (!match) {
return word;
}
const suffix = match[0];
const prefix = word.slice(0, -suffix.length);
const normalizedSuffix = normalizeTrailingSRun(suffix);
return `${prefix}${normalizedSuffix}`;
}
function normalizeMalformedDoubleS(word: string): string {
return normalizeTrailingTripleS(normalizeTripleSBeforeEs(word));
}
function enforceDoubleSPlural(singularWord: string, pluralWord: string): string {
if (!singularWord.toLowerCase().endsWith('ss')) {
return pluralWord;
}
// Defensive normalization for malformed outputs like "hazardClasss".
if (pluralWord === `${singularWord}s`) {
return `${singularWord}es`;
}
return pluralWord;
}
/**
* Convert a word to its singular form with PostGraphile-compatible Latin handling
* @example "Users" -> "User", "People" -> "Person", "Schemata" -> "Schema", "ApiSchemata" -> "ApiSchema"
*/
export function singularize(word: string): string {
const normalizedWord = normalizeMalformedDoubleS(word);
const lowerWord = normalizedWord.toLowerCase();
for (const [pluralSuffix, singularSuffix] of LATIN_SUFFIX_OVERRIDES) {
if (lowerWord.endsWith(pluralSuffix)) {
const suffixStart = normalizedWord.length - pluralSuffix.length;
const prefix = normalizedWord.slice(0, suffixStart);
const originalSuffix = normalizedWord.slice(suffixStart);
const isAllCaps = originalSuffix === originalSuffix.toUpperCase();
const isUpperSuffix =
originalSuffix[0] === originalSuffix[0].toUpperCase();
let newSuffix: string;
if (isAllCaps) {
newSuffix = singularSuffix.toUpperCase();
} else if (isUpperSuffix) {
newSuffix = singularSuffix.charAt(0).toUpperCase() + singularSuffix.slice(1);
} else {
newSuffix = singularSuffix;
}
return prefix + newSuffix;
}
}
// Compound *base words: the inflection library's (b)a branch in the ses$
// rule incorrectly produces "codebasis" instead of "codebase".
const baseMatch = normalizedWord.match(COMPOUND_BASE_REGEX);
if (baseMatch) {
return normalizedWord.slice(0, -1);
}
return normalizeMalformedDoubleS(inflection.singularize(normalizedWord));
}
function pluralizeCanonical(word: string): string {
const normalizedWord = normalizeMalformedDoubleS(word);
const pluralWord = normalizeMalformedDoubleS(inflection.pluralize(normalizedWord));
return enforceDoubleSPlural(singularize(normalizedWord), pluralWord);
}
/**
* Convert a word to its plural form
* @example "User" -> "Users", "Person" -> "People"
*/
export function pluralize(word: string): string {
return pluralizeCanonical(word);
}
/**
* Pluralize/singularize only the final segment of a compound name.
* This is important for names like "user_profiles" where only "profiles" should be pluralized.
*
* @param fn - The singularize or pluralize function to apply
* @param str - The string to transform
* @returns The transformed string with only the final segment changed
*/
function changeLastWord(
fn: (word: string) => string,
str: string
): string {
const matches = str.match(/([A-Z]|_[a-z0-9])[a-z0-9]*_*$/);
const index = matches ? (matches.index ?? 0) + matches[1].length - 1 : 0;
const suffixMatches = str.match(/_*$/);
const suffixIndex =
suffixMatches && suffixMatches.index !== undefined
? suffixMatches.index
: str.length;
const prefix = str.slice(0, index);
const word = str.slice(index, suffixIndex);
const suffix = str.slice(suffixIndex);
return `${prefix}${fn(word)}${suffix}`;
}
/**
* Singularize only the final segment of a compound name
* @example "user_profiles" -> "user_profile", "UserProfiles" -> "UserProfile"
*/
export function singularizeLast(str: string): string {
return changeLastWord(singularize, str);
}
/**
* Pluralize only the final segment of a compound name
* @example "user_profile" -> "user_profiles", "UserProfile" -> "UserProfiles"
*/
export function pluralizeLast(str: string): string {
return changeLastWord(pluralize, str);
}
/**
* Create a distinct plural form, handling cases where singular === plural
* @example "sheep" -> "sheeps" (forced distinct), "user" -> "users"
*/
export function distinctPluralize(str: string): string {
const singular = singularize(str);
const plural = pluralize(singular);
if (singular !== plural) {
return plural;
}
if (
plural.endsWith('ch') ||
plural.endsWith('s') ||
plural.endsWith('sh') ||
plural.endsWith('x') ||
plural.endsWith('z')
) {
return `${plural}es`;
} else if (plural.endsWith('y')) {
return `${plural.slice(0, -1)}ies`;
} else {
return `${plural}s`;
}
}
/**
* Create a distinct plural form for the last word in a compound name
* @example "user_sheep" -> "user_sheeps", "UserSheep" -> "UserSheeps"
*/
export function distinctPluralizeLast(str: string): string {
return changeLastWord(distinctPluralize, str);
}