Created
February 6, 2024 08:31
-
-
Save gaving/265405af2fde381e68c53a3f7235f9b2 to your computer and use it in GitHub Desktop.
pluralize
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
function pluralize(count, word) { | |
// Basic pluralization rules | |
const pluralRules = [ | |
{ match: /(?:ch|sh|ss|x|z)$/, replace: "$&es" }, // Matches words ending in ch, sh, ss, x, z | |
{ match: /([^aeiou])y$/, replace: "$1ies" }, // Changes words ending in y preceded by a consonant to ies | |
{ match: /([^aeiou])o$/, replace: "$1oes" }, // Changes words ending in o preceded by a consonant to oes (e.g., hero to heroes) | |
{ match: /is$/, replace: "es" }, // Special case for words ending in is | |
{ match: /([^aeiou]o)$/, replace: "$1es" }, // Special case for words ending in o preceded by a consonant | |
// Add more rules as needed | |
]; | |
// Irregular plural forms | |
const irregulars = { | |
child: "children", | |
person: "people", | |
man: "men", | |
woman: "women", | |
mouse: "mice", | |
goose: "geese", | |
// Add more irregular forms as needed | |
}; | |
// Return the word if count is 1, else find the plural form | |
if (count === 1) return word; | |
// Check if the word is an irregular form | |
if (irregulars[word.toLowerCase()]) { | |
return irregulars[word.toLowerCase()]; | |
} | |
// Apply pluralization rules | |
for (let i = 0; i < pluralRules.length; i++) { | |
const rule = pluralRules[i]; | |
if (rule.match.test(word)) { | |
return word.replace(rule.match, rule.replace); | |
} | |
} | |
// Default rule: just add "s" | |
return word + "s"; | |
} | |
// Example usage | |
console.log(pluralize(1, 'incident')); // "incident" | |
console.log(pluralize(2, 'incident')); // "incidents" | |
console.log(pluralize(1, 'alias')); // "alias" | |
console.log(pluralize(2, 'alias')); // "aliases" | |
console.log(pluralize(3, 'child')); // "children" | |
console.log(pluralize(2, 'goose')); // "geese" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment