String parser which enables pluralization. Extracted from an internal API logging system I maintain. It is fast, effective and an easy drop in solution. If you would like to see this in a module then please leave a comment.
The function accepts a string
as the first parameter which will contain the plural logic. The second parameter accepts an array
or number
. When you pass an array
of numbers (eg: number[]
) you can reference each index in that array to apply pluralized appenditures based on the position their indexes. If you pass an array
or arrays (eg: any[][]
) the function will fetch the lengths. It is hard to articulate in words, so see the below examples.
Note that
N
is sugar for0
or the first items in the spread.
Below are a couple of example to help you understand how it works.
// Numbers
plural('#{N} #{0} #{1} #{2} #{3}', 1, 2, 3, 4) // => 1, 1, 2, 3, 4
// Arrays
plural('#{N} #{0} #{1} #{2} #{3}', ['x'], ['x','x'], ['x','x','x'], ['x','x','x','x']) // => 1, 1, 2, 3, 4
// Pluralize cat and bird (first value is default)
plural('#{dog} #{cat}{1} #{bird}{2}', 1, 2, 3) // => dog, cats, birds
// Pluralize dog (first value is default)
plural('#{dog} #{cat} #{bird}', 2, 1, 1) // => dogs, cat, bird
// Pluralize birds based on 2nd index (it uses 0 based index when referencing)
plural('#{dog} #{cat} #{bird}{2}', 1, 2, 1) // => dog, cat, birds
// Pluralize dogs and birds based on 2nd and 3rd index (it uses 0 based index when referencing)
plural('#{dog}{1} #{cat} #{bird}{2}', 1, 2, 2) // => dogs, cat, birds
// Pluralize dog and use 2nd value (are) in the literal based on 2nd index in the spread
plural('The #{dog}{1} #{is|are}{1} chasing the #{cat}', 1, 2) // => The dogs are chasing the cat
// Pluralize cat based on 2nd index in the spread
plural('The #{dog} #{is|are} chasing the #{cat}{1}', 1, 2) // => The dog is chasing the cats
Passing a number
Passing a spread of numbers and referencing them based on index position.
plural('#{N} #{person|people} #{is|are} boxing in #{N} #{fight}', 1)
// => 1 person is boxing in 1 fight
plural('#{N} #{person|people} #{is|are} boxing in #{N} #{fight}', 3)
// => 3 people are boxing in 3 fights
Passing a spread of numbers and referencing them based on index position.
plural('#{N} #{person|people} #{is|are} boxing in #{1} #{fight}{1}', 2, 1)
// => 2 people are boxing in 1 fight
plural('#{N} #{person|people} #{is|are} boxing in #{1} #{fight}{1}', 1, 2)
// => 1 person is boxing in 2 fights
Passing a spread of arrays, the function will convert these the index length.
const arr_1 = [{ foo: 'foo' }, { foo: 'bar'}, { foo: 'baz' }]
const arr_2 = ['random', 'values']
plural('#{N} #{person|people} #{is|are} boxing in #{0} #{fight}{1}', arr_1, arr_2)
// => 3 people are boxing in 2 fights
plural('#{N} #{person|people} #{is|are} boxing in #{N} #{fight}', arr_2)
// => 2 people are boxing in 2 fights