|
1 | 1 | import getUserLocale from 'get-user-locale'; |
2 | 2 |
|
| 3 | +const formatterCache = new Map(); |
| 4 | + |
3 | 5 | 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 | + }; |
| 24 | +} |
| 25 | + |
| 26 | +const numberFormatterCache = new Map(); |
| 27 | + |
| 28 | +export function getNumberFormatter(options) { |
| 29 | + return (locale, date) => { |
| 30 | + const localeWithDefault = locale || getUserLocale(); |
| 31 | + |
| 32 | + if (!numberFormatterCache.has(localeWithDefault)) { |
| 33 | + numberFormatterCache.set(localeWithDefault, new Map()); |
| 34 | + } |
| 35 | + |
| 36 | + const numberFormatterCacheLocale = numberFormatterCache.get(localeWithDefault); |
| 37 | + |
| 38 | + if (!numberFormatterCacheLocale.has(options)) { |
| 39 | + numberFormatterCacheLocale.set( |
| 40 | + options, |
| 41 | + new Intl.NumberFormat(localeWithDefault, options).format, |
| 42 | + ); |
| 43 | + } |
| 44 | + |
| 45 | + return numberFormatterCacheLocale.get(options)(date); |
| 46 | + }; |
5 | 47 | } |
6 | 48 |
|
7 | 49 | const formatDateOptions = { day: 'numeric', month: 'numeric', year: 'numeric' }; |
|
0 commit comments