Skip to content

Commit e12564d

Browse files
authored
Add formatter cache (i18next#1843)
* Add formatter cache * Fix unnamed function error
1 parent 69313fc commit e12564d

File tree

1 file changed

+33
-15
lines changed

1 file changed

+33
-15
lines changed

src/Formatter.js

Lines changed: 33 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -39,27 +39,45 @@ function parseFormatStr(formatStr) {
3939
};
4040
}
4141

42+
function createCachedFormatter(fn) {
43+
const cache = Object.create(null);
44+
return function invokeFormatter(val, lng, options) {
45+
const key = lng + JSON.stringify(options);
46+
let formatter = cache[key];
47+
if (!formatter) {
48+
formatter = fn(lng, options);
49+
cache[key] = formatter;
50+
}
51+
return formatter(val);
52+
};
53+
}
54+
4255
class Formatter {
4356
constructor(options = {}) {
4457
this.logger = baseLogger.create('formatter');
4558

4659
this.options = options;
4760
this.formats = {
48-
number: (val, lng, options) => {
49-
return new Intl.NumberFormat(lng, options).format(val);
50-
},
51-
currency: (val, lng, options) => {
52-
return new Intl.NumberFormat(lng, { ...options, style: 'currency' }).format(val);
53-
},
54-
datetime: (val, lng, options) => {
55-
return new Intl.DateTimeFormat(lng, { ...options }).format(val);
56-
},
57-
relativetime: (val, lng, options) => {
58-
return new Intl.RelativeTimeFormat(lng, { ...options }).format(val, options.range || 'day');
59-
},
60-
list: (val, lng, options) => {
61-
return new Intl.ListFormat(lng, { ...options }).format(val);
62-
},
61+
number: createCachedFormatter((lng, options) => {
62+
const formatter = new Intl.NumberFormat(lng, options);
63+
return (val) => formatter.format(val);
64+
}),
65+
currency: createCachedFormatter((lng, options) => {
66+
const formatter = new Intl.NumberFormat(lng, { ...options, style: 'currency' });
67+
return (val) => formatter.format(val);
68+
}),
69+
datetime: createCachedFormatter((lng, options) => {
70+
const formatter = new Intl.DateTimeFormat(lng, { ...options });
71+
return (val) => formatter.format(val);
72+
}),
73+
relativetime: createCachedFormatter((lng, options) => {
74+
const formatter = new Intl.RelativeTimeFormat(lng, { ...options });
75+
return (val) => formatter.format(val, options.range || 'day');
76+
}),
77+
list: createCachedFormatter((lng, options) => {
78+
const formatter = new Intl.ListFormat(lng, { ...options });
79+
return (val) => formatter.format(val);
80+
}),
6381
};
6482
this.init(options);
6583
}

0 commit comments

Comments
 (0)