I18n: Memoize formatDate/formatDuration methods because they're prett… (#90338)

I18n: Memoize formatDate/formatDuration methods because they're pretty slow!!
This commit is contained in:
Josh Hunt 2024-07-12 10:38:47 +01:00 committed by GitHub
parent b321dc7280
commit 03311f6c6c
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 31 additions and 13 deletions

View File

@ -334,6 +334,7 @@
"lucene": "^2.1.1",
"marked": "12.0.2",
"memoize-one": "6.0.0",
"micro-memoize": "^4.1.2",
"ml-regression-polynomial": "^3.0.0",
"ml-regression-simple-linear": "^3.0.0",
"moment": "2.30.1",

View File

@ -1,20 +1,36 @@
import '@formatjs/intl-durationformat/polyfill';
import deepEqual from 'fast-deep-equal';
import memoize from 'micro-memoize';
import { getI18next } from './index';
export function formatDate(value: number | Date | string, format: Intl.DateTimeFormatOptions = {}): string {
if (typeof value === 'string') {
return formatDate(new Date(value), format);
const deepMemoize: typeof memoize = (fn) => memoize(fn, { isEqual: deepEqual });
const createDateTimeFormatter = deepMemoize((language: string, options: Intl.DateTimeFormatOptions) => {
return new Intl.DateTimeFormat(language, options);
});
const createDurationFormatter = deepMemoize((language: string, options: Intl.DurationFormatOptions) => {
return new Intl.DurationFormat(language, options);
});
export const formatDate = deepMemoize(
(value: number | Date | string, format: Intl.DateTimeFormatOptions = {}): string => {
if (typeof value === 'string') {
return formatDate(new Date(value), format);
}
const i18n = getI18next();
const dateFormatter = createDateTimeFormatter(i18n.language, format);
return dateFormatter.format(value);
}
);
const i18n = getI18next();
const dateFormatter = new Intl.DateTimeFormat(i18n.language, format);
return dateFormatter.format(value);
}
export const formatDuration = deepMemoize(
(duration: Intl.DurationInput, options: Intl.DurationFormatOptions = {}): string => {
const i18n = getI18next();
export function formatDuration(duration: Intl.DurationInput, options: Intl.DurationFormatOptions = {}) {
const i18n = getI18next();
const dateFormatter = new Intl.DurationFormat(i18n.language, options);
return dateFormatter.format(duration);
}
const dateFormatter = createDurationFormatter(i18n.language, options);
return dateFormatter.format(duration);
}
);

View File

@ -17344,6 +17344,7 @@ __metadata:
lucene: "npm:^2.1.1"
marked: "npm:12.0.2"
memoize-one: "npm:6.0.0"
micro-memoize: "npm:^4.1.2"
mini-css-extract-plugin: "npm:2.9.0"
ml-regression-polynomial: "npm:^3.0.0"
ml-regression-simple-linear: "npm:^3.0.0"