Skip to content

Commit

Permalink
refactor(money): refactor formatMoney to reuse formatter objects
Browse files Browse the repository at this point in the history
  • Loading branch information
bashunaimiroy committed Nov 27, 2024
1 parent b418abb commit cf9ce33
Showing 1 changed file with 28 additions and 14 deletions.
42 changes: 28 additions & 14 deletions src/helpers/money.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,14 @@ const getCurrencyFractionLength = (currency: string) => {
};

export class Money {

/**
* A private property that stores cached instances of `Intl.NumberFormat`
* for different locale and currency combinations.
* The key is a string representing the locale and currency,
* and the value is the corresponding `Intl.NumberFormat` instance.
*/
#cachedFormatters: { [key: string]: Intl.NumberFormat } = {};
/**
* Formats the Money object based on the provided locale.
*
Expand All @@ -33,20 +41,26 @@ export class Money {
* @returns The formatted amount.
*/
formatAmount(amount: number, currency: string, formattedLocale = 'en-US'): string {
let formatter;
try {
formatter = new Intl.NumberFormat(formattedLocale, {
style: 'currency',
currencyDisplay: 'symbol',
currency: currency
});
} catch (err) {
// Fallback to en-US if it's an invalid BCP 47 locale
formatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currencyDisplay: 'symbol',
currency: currency
});
// use the cached formatter if present, to avoid creating a new formatter every time
const cacheKey = `${currency}:${formattedLocale}`;
let formatter = this.#cachedFormatters[cacheKey];
if (!formatter) {
// create a new formatter for this currency + locale
try {
formatter = new Intl.NumberFormat(formattedLocale, {
style: 'currency',
currencyDisplay: 'symbol',
currency: currency
});
} catch (err) {
// Fallback to en-US if it's an invalid BCP 47 locale
formatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currencyDisplay: 'symbol',
currency: currency
});
}
this.#cachedFormatters[cacheKey] = formatter;
}
amount = this.convertSubunitsToFloat(amount, currency);
return formatter.format(amount);
Expand Down

0 comments on commit cf9ce33

Please sign in to comment.