Skip to content

Commit dabf6c4

Browse files
committed
Cache date formatters
1 parent 3d60c38 commit dabf6c4

File tree

1 file changed

+20
-1
lines changed

1 file changed

+20
-1
lines changed

src/shared/dateFormatter.js

Lines changed: 20 additions & 1 deletion
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
export 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
const formatDateOptions = { day: 'numeric', month: 'numeric', year: 'numeric' };

0 commit comments

Comments
 (0)