Skip to content

Instantly share code, notes, and snippets.

@kyleshevlin
Created May 9, 2020 22:26
Show Gist options
  • Save kyleshevlin/cb158f6f49fccd0971c8211653a2f577 to your computer and use it in GitHub Desktop.
Save kyleshevlin/cb158f6f49fccd0971c8211653a2f577 to your computer and use it in GitHub Desktop.
// Let's learn higher order functions, currying, and partial application
// with a simple, yet useful example
// It's a nice UI touch is to dynamically change a word in a phrase from
// singular to plural based on the quantity of that item
// 4 cats
// 0 dogs
// 1 human
// I call this an "inflection", and like to write this simple helper
// function in my apps
const inflect = singular => plural => quantity => quantity === 1 ? singular : plural
// A higher order function either recieves a function as an argument,
// returns a function, or both. We have a higher order function here,
// because we are returning a new function after each argument.
// A curried function only receives one argument at a time (instead of all
// of them at once). This allows us to "partially apply" values to the
// returned functions
// Partial application is when a function already has a value applied
// because of a closure.
// What does this return?
const humanInflection = inflect('human')('humans')
// It returns this function:
((quantity) => quantity === 1 ? 'human' : 'humans')
// And I can use it over and over again with whatever `quantity` I give it
// I can make other inflections
const indexInflection = inflect('index')('indices')
const datumInflection = inflect('datum')('data')
// And I can use them wherever I want
`I met ${humanQuantity} ${humanInflection(humanQuantity)} today.`
`The array has ${array.length} ${indexInflection(array.length)}`
`I have looked at the `${dataInflection(dataQuantity)}`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment