Kyle Shevlin

Software Engineer

Snippet

inflect()

edit
0 strokes bestowed

Often nouns need slight changes depending on the quantity of that noun. Example: One person, several people. I call these differences "inflections". The inflect function below is a little helper function I use to help me apply inflections in my application.

const inflect =
  (singular, plural = `${singular}s`) =>
  quantity =>
    Math.abs(quantity) === 1 ? singular : plural

inflect is a higher order function, meaning it's a function that returns a function. If you need some info on higher order functions, check out my post on them and the post on currying.

This solution makes use of default parameters for the plural argument. If adding an "s" is all you need to make a plural, then you don't need to provide it. Like this:

const inflectPost = inflect('post')

console.log(inflectPost(1)) // 'post'
console.log(inflectPost(2)) // 'posts'

But often plurals have oddities (like "person" and "people"), so you can supply a plural argument when you need it.

const inflectMouse = inflect('mouse', 'mice')
const inflectKnife = inflect('knife', 'knives')
// etc

Now, as helpful as this is, it is not a proper solution should you need internationalization. Treat this is a helper function for those instances this can support.


Finished reading?

Here are a few options for what to do next.

Like
Liked the post? Click the beard up to 50 times to show it
Share
Sharing this post on Twitter & elsewhere is a great way to help me out
Support
Was this post valuable to you? Make a donation to show it
Make a Donation
Kofi logo

Kyle Shevlin's face, which is mostly a beard with eyes
Kyle Shevlin is a software engineer who specializes in JavaScript, React and front end web development.

Let's talk some more about JavaScript, React, and software engineering.

I write a newsletter to share my thoughts and the projects I'm working on. I would love for you to join the conversation. You can unsubscribe at any time.

Array.reduce() Logo
Array.reduce()

Check out my courses!

Liked the post? You might like my courses, too. Click the button to view this course or go to Courses for more information.
I would like give thanks to those who have contributed fixes and updates to this blog. If you see something that needs some love, you can join them. This blog is open sourced at https://github.com/kyleshevlin/blog
alexloudenjacobwsmithbryndymentJacobMGEvanseclectic-codingjhsukgcreativeerikvorhesHaroenvmarktnoonandependabotmarcuslyonsbrentmclarkfederico-fiorinimedayzDoNormal
©2021 Kyle Shevlin. All Rights Reserved.