Skip to content

Instantly share code, notes, and snippets.

@hoodwink73
Created November 13, 2019 11:39
Show Gist options
  • Save hoodwink73/c16a3a76d44fbbf9cd48d89765079aa9 to your computer and use it in GitHub Desktop.
Save hoodwink73/c16a3a76d44fbbf9cd48d89765079aa9 to your computer and use it in GitHub Desktop.
Template tag for pluralise
// this is a tagged template function
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#Tagged_templates
// Example
// pluralize`You have ${events.length} ${["meeting","meetings"]} today`
export default function pluralize(
strings,
num,
[singularWord, pluralWord] = []
) {
let word, emptyWord;
let result = "";
if (!num) {
return strings.join("");
}
if (num.length) {
emptyWord = num[1];
num = num[0];
}
if (num === 0) {
num = emptyWord;
word = singularWord;
} else if (num > 1) {
word = pluralWord;
} else {
word = singularWord;
}
const interpolatedParts = [num < 1 ? emptyWord : num, word, ""];
for (let i in strings) {
result += strings[i] + interpolatedParts[i];
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment