Skip to content

JoschuaSchneider/mehrzahl

Repository files navigation

mehrzahl

npm version Bundlephobia Minzipped Size build workflow test workflow TypeScript License: MIT

Tiny utility to format parts of a template string in singular or plural.

Installation

npm i mehrzahl
yarn add mehrzahl

Usage

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."

Reversed usage

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.

Singular/Plural tuples

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."

Customizing the delimiter

Pass your custom delimiter as a second argument.

const str = mz(1, ';')`There {was;were} $value person{;s} at this event.`

Contributions

Contributions are always welcome.

Feel free to open issues or pull requests!