The last two weeks, I've been making some new Hacktoberfest contributions but I did not write about them. Let's fix that! In this post I will talk about my contribution to mehrzahl.
Mehrzahl is a little npm module to format parts of a template string in singular or plural. Here is the npm page and this is how it works:
import { mz } from "mehrzahl"
const str = mz(3)`There {is|are} $value bird{|s} at the park.`
// str = "There are 3 birds at the park."
The issue
The issue I worked on was to add a reverse usage of the mz
utility (and calling it zm
) to accomplish this:
import { zm } from "mehrzahl"
const template = zm`There {was|were} $value bird{|s} at the park.`
template(5) // There were 5 birds at the park.
template(1) // There was 1 bird at the park.
The solution
After writing the new zm
function, I noticed there was a lot of repeated code between mz
and zm
. I decided to refactor and write a mehrzahl
function to handle the common parts.
const mehrzahl = (
amount: number,
delimiter: string,
strings: TemplateStringsArray,
...valuesToInterpolate: InterpolatableValue[]
) => {
[...]
}
I modified the original mz
function to use the new mehrzahl
function:
export const mz: MehrzahlFormatterFactory =
(amount, delimiter = DEFAULT_DELIMITER) =>
(strings, ...valuesToInterpolate) => {
return mehrzahl(
amount,
delimiter,
strings,
...valuesToInterpolate
)
}
And the zm
function to do the same:
export const zm: ReversedMehrzahlFormatterFactory =
(strings, ...valuesToInterpolate) =>
(amount, delimiter = DEFAULT_DELIMITER) => {
return mehrzahl(
amount,
delimiter,
strings,
...valuesToInterpolate
)
}
Of course to get the reversed effect, I had to create two new types ReversedMehrzahlFormatterFactory
and ReversedMerzahlFormatter
.
The maintainer of the project Joschua Schneider was super nice and he added some helpful comments on my Pull Request (such as suggesting the names he was looking for). Joschua is a student from Germany and he wrote the original code on his own. I am the first one to add new functionality to his little utility and it was a lot of fun. I ofter think of Github as the place where you can find big open source projects but I tend to forget that there are millions of users creating all sorts of fun little projects like this one. The hardest part is always finding them!
Top comments (0)