Created
November 13, 2019 11:39
-
-
Save hoodwink73/c16a3a76d44fbbf9cd48d89765079aa9 to your computer and use it in GitHub Desktop.
Template tag for pluralise
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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