Translate Messages with Plural Forms

Write the code, see it run, pass the checks.

The problem

  • medium
  • Code

Write createTranslator(messages), which returns t(key, values) for looking up interface text. messages maps each key to either a string, such as "Hello, {name}!", or a plural message: an object with an other form and, optionally, zero and one forms, such as { one: "{count} item", other: "{count} items" }. For a plural message, values.count picks the form by the English rule: zero when count is 0 and the message has a zero form, one when count is exactly 1 and it has a one form, and other for everything else, including 0 without a zero form, and 1.5. Write the rule yourself: Intl.PluralRules isn't available in the checks. If count is missing or isn't a number, throw a TypeError. Then replace each placeholder, a name of letters, digits and underscores in curly braces, with String(values[name]), so 0 shows as "0"; a placeholder whose value is missing, null or undefined stays as it is. Values are inserted exactly as they are, even if they contain a $. values may be left out, and a key with no message returns the key itself.

Your code must pass

  • Fills placeholders in simple messages
  • Leaves placeholders without a value as they are
  • Picks the one and other forms by the English rule
  • Uses the zero form only when the message has one
  • Falls back to the key for missing messages
  • Throws a TypeError when a plural message has no count