Skip to content

Instantly share code, notes, and snippets.

@gm50x
Created August 9, 2020 19:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gm50x/624001610eacfc8569652e7bd742093c to your computer and use it in GitHub Desktop.
Save gm50x/624001610eacfc8569652e7bd742093c to your computer and use it in GitHub Desktop.
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()
@bmomani1
Copy link

thank you for your effort

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment