Skip to content

Instantly share code, notes, and snippets.

@chroder
Last active October 10, 2018 12:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chroder/914d33c3b25cd5a974f0ea63192e1e1e to your computer and use it in GitHub Desktop.
Save chroder/914d33c3b25cd5a974f0ea63192e1e1e to your computer and use it in GitHub Desktop.
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