[Perf] Cache for formatDateToString

This commit is contained in:
Alexander Zinchuk 2022-03-19 21:18:51 +01:00
parent 1172e791e6
commit 5500fb0d50
2 changed files with 18 additions and 5 deletions

View File

@ -1,7 +1,7 @@
import { ApiMessage } from '../../../api/types';
import { IAlbum } from '../../../types';
import { getDayStart } from '../../../util/dateFormat';
import { getDayStartAt } from '../../../util/dateFormat';
import { isActionMessage } from '../../../modules/helpers';
type SenderGroup = (ApiMessage | IAlbum)[];
@ -22,7 +22,7 @@ export function groupMessages(messages: ApiMessage[], firstUnreadId?: number) {
let currentSenderGroup: SenderGroup = [];
let currentDateGroup = {
originalDate: messages[0].date,
datetime: Number(getDayStart(messages[0].date * 1000)),
datetime: getDayStartAt(messages[0].date * 1000),
senderGroups: [currentSenderGroup],
};
let currentAlbum: IAlbum | undefined;
@ -57,7 +57,7 @@ export function groupMessages(messages: ApiMessage[], firstUnreadId?: number) {
currentAlbum = undefined;
}
if (nextMessage) {
const nextMessageDayStartsAt = Number(getDayStart(nextMessage.date * 1000));
const nextMessageDayStartsAt = getDayStartAt(nextMessage.date * 1000);
if (currentDateGroup.datetime !== nextMessageDayStartsAt) {
currentDateGroup = {
originalDate: nextMessage.date,

View File

@ -13,7 +13,7 @@ const MAX_MONTH_IN_YEAR = 12;
export const MILLISECONDS_IN_DAY = 24 * 60 * 60 * 1000;
export function isToday(date: Date) {
return getDayStart(new Date()) === getDayStart(date);
return getDayStartAt(new Date()) === getDayStartAt(date);
}
export function getDayStart(datetime: number | Date) {
@ -246,9 +246,18 @@ export function formatVoiceRecordDuration(durationInMs: number) {
return `${parts.join(':')},${String(milliseconds).padStart(2, '0')}`;
}
// `toLocaleString` is slow so we use cache
const dateFormatCache = new Map<string, string>();
export function formatDateToString(datetime: Date | number, locale = 'en-US') {
const date = typeof datetime === 'number' ? new Date(datetime) : datetime;
return date.toLocaleString(
const cacheKey = `${locale}_${getDayStartAt(date)}`;
const cached = dateFormatCache.get(cacheKey);
if (cached) {
return cached;
}
const newValue = date.toLocaleString(
locale,
{
year: 'numeric',
@ -256,6 +265,10 @@ export function formatDateToString(datetime: Date | number, locale = 'en-US') {
day: 'numeric',
},
);
dateFormatCache.set(cacheKey, newValue);
return newValue;
}
export function formatDateTimeToString(datetime: Date | number, locale = 'en-US') {