Skip to content

Commit cc4d12d

Browse files
committed
Fix memory leak when calling getFormatter
1 parent 451b8f0 commit cc4d12d

File tree

1 file changed

+30
-12
lines changed

1 file changed

+30
-12
lines changed

src/DateTimeInput.jsx

Lines changed: 30 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,8 @@ import { convert12to24, convert24to12 } from './shared/dates';
2727
import { isMaxDate, isMinDate } from './shared/propTypes';
2828
import { between, getAmPmLabels } from './shared/utils';
2929

30+
const getFormatterOptionsCache = {};
31+
3032
const defaultMinDate = new Date();
3133
defaultMinDate.setFullYear(1, 0, 1);
3234
defaultMinDate.setHours(0, 0, 0, 0);
@@ -230,16 +232,24 @@ export default class DateTimeInput extends PureComponent {
230232
get formatTime() {
231233
const { maxDetail } = this.props;
232234

233-
const options = { hour: 'numeric' };
234235
const level = allViews.indexOf(maxDetail);
235-
if (level >= 1) {
236-
options.minute = 'numeric';
237-
}
238-
if (level >= 2) {
239-
options.second = 'numeric';
240-
}
241-
242-
return getFormatter(options);
236+
const formatterOptions =
237+
getFormatterOptionsCache[level] ||
238+
(() => {
239+
const options = { hour: 'numeric' };
240+
if (level >= 1) {
241+
options.minute = 'numeric';
242+
}
243+
if (level >= 2) {
244+
options.second = 'numeric';
245+
}
246+
247+
getFormatterOptionsCache[level] = options;
248+
249+
return options;
250+
})();
251+
252+
return getFormatter(formatterOptions);
243253
}
244254

245255
get formatNumber() {
@@ -268,9 +278,17 @@ export default class DateTimeInput extends PureComponent {
268278
const datePieceReplacements = ['y', 'M', 'd'];
269279

270280
function formatDatePiece(name, dateToFormat) {
271-
return getFormatter({ useGrouping: false, [name]: 'numeric' })(locale, dateToFormat).match(
272-
/\d{1,}/,
273-
);
281+
const formatterOptions =
282+
getFormatterOptionsCache[name] ||
283+
(() => {
284+
const options = { useGrouping: false, [name]: 'numeric' };
285+
286+
getFormatterOptionsCache[name] = options;
287+
288+
return options;
289+
})();
290+
291+
return getFormatter(formatterOptions)(locale, dateToFormat).match(/\d{1,}/);
274292
}
275293

276294
let placeholder = formattedDate;

0 commit comments

Comments
 (0)