Tagged template literals for singular/plural formatting
npm install mehrzahl
!Bundlephobia Minzipped Size
!build workflow
!test workflow
!TypeScript
!License: MIT
Tiny utility to format parts of a template string in singular or plural.
``bash`
npm i mehrzahl`bash`
yarn add mehrzahl
`ts
import { mz } from "mehrzahl"
// import mz from "mehrzahl" // default import
const str = mz(1)There {was|were} $value person{|s} at this event.There {was|were} $value person{|s} at this event.
// str = "There was 1 person at this event."
const str = mz(5)`
// str = "There were 5 persons at this event."zm
#### Reversed usage
You can use the exported function to create a function curried with the template first and then calling it with the amount:`ts
import { zm } from "mehrzahl"
const template = zmThere {was|were} $value person{|s} at this event.`
template(5) // There were 5 persons at this event.
template(0) // There was 1 person at this event.
š” $value is replaced by the amount specified.
#### Singular/Plural tuples
`tsThere ${['was', 'were']} $value person${[,'s']} at this event.
const str = mz(1)There ${['was', 'were']} $value person${[,'s']} at this event.
// str = "There was 1 person at this event."
const str = mz(5)`
// str = "There were 5 persons at this event."
š” Left or right value of the delimiter | can be omitted:{|plural} or {singular|}
š” First or second value of tuples can be omitted:
[,'plural'] or ['singular']
Singular/Plural formatter function
`ts
const wasWereFormatter = (plural) => plural ? 'were' : 'was'
const personPersonsFormatter = (plural) => plural ? 'persons' : 'person'
const str = mz(1)There ${wasWereFormatter} $value ${personPersonsFormatter} at this event.There ${wasWereFormatter} $value ${personPersonsFormatter} at this event.
// str = "There was 1 person at this event."
const str = mz(5)`
// str = "There were 5 persons at this event."
#### Customizing the delimiter
Pass your custom delimiter as a second argument.
`tsThere {was;were} $value person{;s} at this event.
const str = mz(1, ';')``
Contributions are always welcome.
Feel free to open issues or pull requests!