Pluralize
This utility function returns the plural or singular form of an English word based on count.
ts1interface IrregularPlurals { 2 [key: string]: string; 3} 4 5/** 6 * Returns the plural or singular form of an English word based on count 7 * @param word - The word to pluralize/singularize 8 * @param count - The count determining plural or singular form 9 * @returns The appropriate form of the word 10 */ 11export function pluralize(word: string, count: number): string { 12 const irregularPlurals: IrregularPlurals = { 13 child: "children", 14 person: "people", 15 man: "men", 16 woman: "women", 17 tooth: "teeth", 18 foot: "feet", 19 mouse: "mice", 20 goose: "geese", 21 }; 22 23 if (count === 1) { 24 return word; 25 } 26 27 const lowerWord = word.toLowerCase(); 28 /* eslint-disable security/detect-object-injection */ 29 if (irregularPlurals[lowerWord]) { 30 return irregularPlurals[lowerWord]; 31 } 32 /* eslint-enable security/detect-object-injection */ 33 34 if (word.endsWith("y")) { 35 const vowels: Array<string> = ["a", "e", "i", "o", "u"]; 36 if (!vowels.includes(word.at(-2) ?? "")) { 37 return word.slice(0, -1) + "ies"; 38 } 39 } 40 41 if ( 42 word.endsWith("s") || 43 word.endsWith("sh") || 44 word.endsWith("ch") || 45 word.endsWith("x") || 46 word.endsWith("z") 47 ) { 48 return word + "es"; 49 } 50 51 if (word.endsWith("f")) { 52 return word.slice(0, -1) + "ves"; 53 } 54 if (word.endsWith("fe")) { 55 return word.slice(0, -2) + "ves"; 56 } 57 58 return word + "s"; 59}
Usage
tsx1<span>{pluralize("like", like_count)}</span>