diff --git a/ui/util/format-credits.js b/ui/util/format-credits.js index a32dac0ca..67faf687a 100644 --- a/ui/util/format-credits.js +++ b/ui/util/format-credits.js @@ -1,3 +1,5 @@ +import { getFormatter } from './intlNumberFormat'; + export function formatCredits(amount, precision, shortFormat = false) { const language = localStorage.getItem('language') || undefined; const actualAmount = Number(amount); @@ -6,7 +8,7 @@ export function formatCredits(amount, precision, shortFormat = false) { if (Number.isNaN(actualAmount) || actualAmount === 0) return '0'; if (shortFormat) { - const formatter = new Intl.NumberFormat(language, { + const formatter = getFormatter(language, { minimumFractionDigits: safePrecision, maximumFractionDigits: safePrecision, roundingIncrement: 5, @@ -17,7 +19,7 @@ export function formatCredits(amount, precision, shortFormat = false) { return formatter.format(actualAmount); } - const formatter = new Intl.NumberFormat(language, { + const formatter = getFormatter(language, { minimumFractionDigits: safePrecision, maximumFractionDigits: safePrecision, roundingIncrement: 5, diff --git a/ui/util/intlNumberFormat.js b/ui/util/intlNumberFormat.js new file mode 100644 index 000000000..94a5a5a44 --- /dev/null +++ b/ui/util/intlNumberFormat.js @@ -0,0 +1,14 @@ +// @flow +const formatterCache = {}; + +// Creating multiple Intl.NumberFormat instances can +// be expensive, that's why we perform a very simple +// cache. +// See https://github.com/formatjs/formatjs/issues/27#issuecomment-61148808 +export function getFormatter(language?: string, options: any) { + const key = `${language || ''}:${JSON.stringify(options || {})}`; + if (!formatterCache[key]) { + formatterCache[key] = new Intl.NumberFormat(language, options); + } + return formatterCache[key]; +} diff --git a/ui/util/number.js b/ui/util/number.js index b24476356..1b2bdea94 100644 --- a/ui/util/number.js +++ b/ui/util/number.js @@ -1,9 +1,10 @@ // @flow +import { getFormatter } from './intlNumberFormat'; export function formatNumber(num: number, numberOfDigits?: number, short: boolean = false): string { const language = localStorage.getItem('language') || undefined; const safePrecision = Math.min(20, numberOfDigits || 0); - const formatter = new Intl.NumberFormat(language, { + const formatter = getFormatter(language, { maximumFractionDigits: safePrecision, notation: short ? 'compact' : 'standard', compactDisplay: 'short',