perf: Improve getAggregatedAvailability by reducing reliance on Day.js (#11224)

pull/11229/head
Alex van Andel 2023-09-08 11:19:27 +01:00 committed by GitHub
parent f25f8e0909
commit 3132c64205
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 15 additions and 7 deletions

View File

@ -22,25 +22,33 @@ export const getAggregatedAvailability = (
return mergeOverlappingDateRanges(availability);
};
function isSameDay(date1: Date, date2: Date) {
return (
date1.getUTCFullYear() === date2.getUTCFullYear() &&
date1.getUTCMonth() === date2.getUTCMonth() &&
date1.getUTCDate() === date2.getUTCDate()
);
}
function mergeOverlappingDateRanges(dateRanges: DateRange[]) {
const sortedDateRanges = dateRanges.sort((a, b) => a.start.diff(b.start)); //is it already sorted before?
dateRanges.sort((a, b) => a.start.valueOf() - b.start.valueOf());
const mergedDateRanges: DateRange[] = [];
let currentRange = sortedDateRanges[0];
let currentRange = dateRanges[0];
if (!currentRange) {
return [];
}
for (let i = 1; i < sortedDateRanges.length; i++) {
const nextRange = sortedDateRanges[i];
for (let i = 1; i < dateRanges.length; i++) {
const nextRange = dateRanges[i];
if (
currentRange.start.utc().format("DD MM YY") === nextRange.start.utc().format("DD MM YY") &&
currentRange.end.isAfter(nextRange.start)
isSameDay(currentRange.start.toDate(), nextRange.start.toDate()) &&
currentRange.end.valueOf() > nextRange.start.valueOf()
) {
currentRange = {
start: currentRange.start,
end: currentRange.end.isAfter(nextRange.end) ? currentRange.end : nextRange.end,
end: currentRange.end.valueOf() > nextRange.end.valueOf() ? currentRange.end : nextRange.end,
};
} else {
mergedDateRanges.push(currentRange);