Skip to content

Commit e895271

Browse files
committed
Cache date formatters
Closes #180
1 parent 0565ca0 commit e895271

File tree

2 files changed

+40
-2
lines changed

2 files changed

+40
-2
lines changed

src/shared/dateFormatter.js

+20-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,26 @@
11
import getUserLocale from 'get-user-locale';
22

3+
const formatterCache = new Map();
4+
35
function getFormatter(options) {
4-
return (locale, date) => date.toLocaleString(locale || getUserLocale(), options);
6+
return (locale, date) => {
7+
const localeWithDefault = locale || getUserLocale();
8+
9+
if (!formatterCache.has(localeWithDefault)) {
10+
formatterCache.set(localeWithDefault, new Map());
11+
}
12+
13+
const formatterCacheLocale = formatterCache.get(localeWithDefault);
14+
15+
if (!formatterCacheLocale.has(options)) {
16+
formatterCacheLocale.set(
17+
options,
18+
new Intl.DateTimeFormat(localeWithDefault, options).format,
19+
);
20+
}
21+
22+
return formatterCacheLocale.get(options)(date);
23+
};
524
}
625

726
/**

test/shared/dateFormatter.js

+20-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,26 @@
11
import getUserLocale from 'get-user-locale';
22

3+
const formatterCache = new Map();
4+
35
function getFormatter(options) {
4-
return (locale, date) => date.toLocaleString(locale || getUserLocale(), options);
6+
return (locale, date) => {
7+
const localeWithDefault = locale || getUserLocale();
8+
9+
if (!formatterCache.has(localeWithDefault)) {
10+
formatterCache.set(localeWithDefault, new Map());
11+
}
12+
13+
const formatterCacheLocale = formatterCache.get(localeWithDefault);
14+
15+
if (!formatterCacheLocale.has(options)) {
16+
formatterCacheLocale.set(
17+
options,
18+
new Intl.DateTimeFormat(localeWithDefault, options).format,
19+
);
20+
}
21+
22+
return formatterCacheLocale.get(options)(date);
23+
};
524
}
625

726
/**

0 commit comments

Comments
 (0)