Tiny utility to format parts of a template string in singular or plural.
npm i mehrzahl
yarn add mehrzahl
import { mz } from "mehrzahl"
// import mz from "mehrzahl" // default import
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)`There {was|were} $value person{|s} at this event.`
// str = "There were 5 persons at this event."
You can use the exported zm
function to create a function curried with the template first and then calling it with the amount:
import { zm } from "mehrzahl"
const template = zm`There {was|were} $value person{|s} at this event.`
template(5) // There were 5 persons at this event.
template(1) // There was 1 person at this event.
💡 $value
is replaced by the amount specified.
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)`There ${['was', 'were']} $value person${[,'s']} at this event.`
// 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
const wasWereFormatter = (plural) => plural ? 'were' : 'was'
const personPersonsFormatter = (plural) => plural ? 'persons' : 'person'
const str = mz(1)`There ${wasWereFormatter} $value ${personPersonsFormatter} at this event.`
// str = "There was 1 person at this event."
const str = mz(5)`There ${wasWereFormatter} $value ${personPersonsFormatter} at this event.`
// str = "There were 5 persons at this event."
Pass your custom delimiter as a second argument.
const str = mz(1, ';')`There {was;were} $value person{;s} at this event.`
Contributions are always welcome.
Feel free to open issues or pull requests!