formatjs / intl-messageformat

[MIGRATED] Format a string with placeholders, including plural and select support to create localized messages.
http://formatjs.io/
Other
530 stars 77 forks source link

Setting formats (options) dynamically #134

Closed cwallervand closed 5 years ago

cwallervand commented 8 years ago

Hey.

It would be great if it was possible to set formatting options after creating the IntlMessageFormat object. Something like this:

let msg = new IntlMessageFormat('The price is: {price, number, formatOptions}', 'en-US');
msg.setOptions({
    number: {
        formatOptions: {
            style   : 'currency',
            currency: 'USD'
        }
    }
});

const output = msg.format({price: 100});

In many cases where we format numbers we use the same message template, but with different formatting options e.g. with two decimals, without decimals, etc. Being able to set format options after creating the IntlMessageFormat object means that you dont have to create a new object instance, which we do now. This can affect performance of applications when objects are created and destroyed rappidly.

caridy commented 8 years ago

Creating Intl instances is way more expensive than creating JS objects. e.g.:

new Intl.NumberFormat(location, options);

Since it requires ICU/CLDR underlaying integration, which requires some bridge crossing from the engine to ICU, this operation is slow. Intl.MessageFormat is not part of the engine just yet, but it relies on the creation of a plural rule instance (https://github.com/tc39/proposal-intl-plural-rules/) and/or number format instance, which makes this expensive.

Moving all the logic to the .format is doable, but you will get penalize for extra operations during format, and introducing a setOptions() method diverge from other standard Intl mechanism, and IMO buy us little.