Add Intl.NumberFormat cache.
This commit is contained in:
parent
efa682ef02
commit
3671e855cb
3 changed files with 20 additions and 3 deletions
|
@ -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,
|
||||
|
|
14
ui/util/intlNumberFormat.js
Normal file
14
ui/util/intlNumberFormat.js
Normal file
|
@ -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];
|
||||
}
|
|
@ -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',
|
||||
|
|
Loading…
Reference in a new issue