Skip to content

Instantly share code, notes, and snippets.

@rxaviers
Last active August 29, 2015 14:01
Show Gist options
  • Save rxaviers/f3e89211b47bf36fc4a2 to your computer and use it in GitHub Desktop.
Save rxaviers/f3e89211b47bf36fc4a2 to your computer and use it in GitHub Desktop.
Talks about Globalize, Cldr.js, plural and messages

Let's consider the following data.

{
  "main": {
    "en": {
      "units": {
        "long": {
          "per": {
            "compoundUnitPattern": "{0} per {1}"
          },
          "duration-day": {
            "unitPattern-count-one": "{0} day",
            "unitPattern-count-other": "{0} days"
          }
        }
      }
    }
  }
}

Code

Cldr.load( /* let's consider we loaded everything that's necessary */ )

en = new Cldr("en");
en.main("units/long/days");
// "duration-day": {
//   "unitPattern-count-one": "{0} day",
//   "unitPattern-count-other": "{0} days"
// }

First of all, ideally there should be no unitPattern-count- on the keys before the plural count. Let's assume we have this instead:

en.main("units/long/days");
// "duration-day": {
//   "one": "{0} day",
//   "other": "{0} days"
// }

How should we get the proper plural portion?

var days = 20;

en.main(["units/long/days", plural(en, days)]);
// "{0} days"

Using Globalize:

Globalize(en).formatPlural(en.main("units/long/days"), days);
// "{0} days"

Now, we need to replace {x} variables.

en.main(["units/long/days", plural(en, days)]).replace( /{0}/, days );
// "20 days"

Using Globalize:

Globalize(en).formatMessage( prevStr, [days] );
// "20 days"

Replacing such variables is the most basic functionality of MessageFormat.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment