Created
August 9, 2020 19:41
-
-
Save gm50x/624001610eacfc8569652e7bd742093c to your computer and use it in GitHub Desktop.
This file contains 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
const wordPlural = (word, amount) => { | |
word = word.toLowerCase() | |
if (amount === 1) { | |
return word | |
} | |
return pluralize(word) | |
} | |
const pluralize = word => { | |
return getPluralRule(word) | |
.pluralize(word) | |
} | |
const getPluralRule = word => { | |
const exceptions = { | |
roof: 'roofs', | |
belief: 'beliefs', | |
chef: 'chefs', | |
chief: 'chiefs', | |
gas: 'gasses', | |
fez: 'fezzes', | |
man: 'men', | |
woman: 'women', | |
child: 'children', | |
goose: 'geese', | |
tooth: 'teeth' | |
} | |
if (exceptions[word]) { | |
return { pluralize: word => exceptions[word] } | |
} | |
const rules = [ | |
{ matcher: '(sh|s+|ch|x|z)$', pluralize: word => `${word}es` }, | |
{ matcher: '(f|fe)$', pluralize: word => word.replace(/(f|fe)$/, 'ves') }, | |
{ matcher: '[^aeiou]y$', pluralize: word => word.replace(/y$/, 'ies') }, | |
{ matcher: '[aeiou]y$', pluralize: word => `${word}s` }, | |
{ matcher: 'o$', pluralize: word => `${word}es` }, | |
{ matcher: '[a-z]+$', pluralize: word => `${word}s` } | |
] | |
return rules | |
.find(p => new RegExp(p.matcher).test(word)) | |
} | |
const main = () => { | |
const words = [ | |
'car', 'goose', 'banana', 'roof', 'belief', | |
'elf', 'knife', 'gas', 'watch', 'batch', | |
'bus', 'tooth', 'truss', 'lunch', 'wolf', | |
'rubber', 'computer', 'headset', 'tomato', 'potato', | |
'shrimp', 'man', 'clock', 'hand', 'wall', | |
'room', 'mind', 'calling', 'breath', 'life'] | |
const logger = (word, i) => { | |
if (i === 0) { | |
console.log('iteration ==> singular ==> plural') | |
} | |
console.log(`${(i + 1).toString().padStart(2, '0').padEnd(9, ' ')} ==> ${wordPlural(word, 1).padEnd(8, ' ')} ==> ${wordPlural(word, 2)}`) | |
} | |
words.forEach(logger) | |
} | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thank you for your effort