Last active
October 10, 2018 12:48
-
-
Save chroder/914d33c3b25cd5a974f0ea63192e1e1e to your computer and use it in GitHub Desktop.
This file contains 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
const phrases = { | |
"new_messages": "You have 1 new message", | |
"new_messages_plural": "You have {{count}} new messages" | |
} | |
function formatPhrase(id, vars = {}) { | |
// If there's a count, then we | |
// we need to select the plural variant | |
if ( | |
typeof vars.count != "undefined" && | |
vars.count != 1 && | |
!id.match(/_plural$/) | |
) { | |
return formatPhrase(`${id}_plural`, vars); | |
} | |
// replace vars with the actual values | |
return Object.entries(vars).reduce( | |
(p, [key, value]) => p.replace("{{"+key+"}}", value), | |
phrases[id] | |
); | |
} | |
console.log(formatPhrase("new_messages", { count: 0 })); | |
console.log(formatPhrase("new_messages", { count: 1 })); | |
console.log(formatPhrase("new_messages", { count: 2 })); | |
// You have 0 new messages | |
// You have 1 new message | |
// You have 2 new messages |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment