Merge pull request #1 from THoguet/copilot/identify-improve-slow-code

Optimize vacation algorithm: reduce O(n²) lookups and eliminate redundant Date allocations
This commit is contained in:
Théophyl Hoguet authored and GitHub committed 2025-11-03 18:53:15 +01:00
commit e2ed512b11
7 files changed
+303 -91

No files matched your search

+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "vac-optimizer",
"version": "0.0.0",
"version": "1.5.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "vac-optimizer",
"version": "0.0.0",
"version": "1.5.0",
"dependencies": {
"@angular/cdk": "^20.2.10",
"@angular/common": "^20.3.0",
@@ -1,7 +1,8 @@
import { Component, Input, OnInit } from '@angular/core';
import { Component, Input, OnInit, inject } from '@angular/core';
import { CalendarService, Month, monthNames, SelectedDates } from '../../services/calendar-service';
import { MatTooltip } from '@angular/material/tooltip';
import { CalendarSettingsService } from '../../services/calendar-settings-service';
import { DateCacheService } from '../../services/date-cache.service';
@Component({
selector: 'app-calendar-month',
@@ -10,7 +11,8 @@ import { CalendarSettingsService } from '../../services/calendar-settings-servic
styleUrl: './calendar-month.scss',
})
export class CalendarMonth implements OnInit {
constructor(protected calendarSettingsService: CalendarSettingsService) {}
protected calendarSettingsService = inject(CalendarSettingsService);
private dateCache = inject(DateCacheService);
@Input({ required: true })
monthIndex!: number;
@@ -18,10 +20,9 @@ export class CalendarMonth implements OnInit {
@Input({ required: true })
year!: number;
// Use DateCacheService instead of creating Date objects
getNow(): Date {
const now = new Date();
now.setHours(0, 0, 0, 0);
return now;
return this.dateCache.getNow();
}
currentMonth: Date = new Date();
@@ -1,4 +1,4 @@
import { Component, effect, signal } from '@angular/core';
import { Component, effect, signal, inject } from '@angular/core';
import { UserInputService } from '../../services/user-input-service';
import { MatCard, MatCardContent } from '@angular/material/card';
import { CalendarMonth } from '../calendar-month/calendar-month';
@@ -6,6 +6,7 @@ import { CalendarService, SelectedDates } from '../../services/calendar-service'
import { CommonModule } from '@angular/common';
import { MatProgressSpinner } from '@angular/material/progress-spinner';
import { CalendarSettingsService } from '../../services/calendar-settings-service';
import { DateCacheService } from '../../services/date-cache.service';
@Component({
selector: 'app-calendar-year',
@@ -14,13 +15,23 @@ import { CalendarSettingsService } from '../../services/calendar-settings-servic
styleUrl: './calendar-year.scss',
})
export class CalendarYear {
private dateCache = inject(DateCacheService);
private userInput = inject(UserInputService);
private calendarService = inject(CalendarService);
private calendarSettingsService = inject(CalendarSettingsService);
protected isLoading = signal(true);
constructor(
private userInput: UserInputService,
private calendarService: CalendarService,
private calendarSettingsService: CalendarSettingsService,
) {
// Use DateCacheService instead of creating Date objects
private get currentMonth() {
return this.dateCache.getCurrentMonth();
}
private get currentYear() {
return this.dateCache.getCurrentYear();
}
constructor() {
effect(() => {
this.selectedDates = this.calendarService.getSelectedDatesForYear();
const vacationData = this.userInput.vacationNumberSignal();
@@ -45,13 +56,10 @@ export class CalendarYear {
protected selectedDates: SelectedDates = new SelectedDates();
getYear(monthIndex: number): number {
const offset = new Date().getMonth() <= monthIndex ? 0 : 1;
return new Date().getFullYear() + offset;
const offset = this.currentMonth <= monthIndex ? 0 : 1;
return this.currentYear + offset;
}
// months starting from actual date
protected months: number[] = Array.from(
{ length: 12 },
(_, i) => (new Date().getMonth() + i) % 12,
);
// months starting from actual date - cache this array
protected months: number[] = Array.from({ length: 12 }, (_, i) => (this.currentMonth + i) % 12);
}
+4 -4
View File
@@ -1,13 +1,13 @@
import { TestBed } from '@angular/core/testing';
import { Calendar } from './calendar';
import { CalendarService } from './calendar-service';
describe('Calendar', () => {
let service: Calendar;
describe('CalendarService', () => {
let service: CalendarService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(Calendar);
service = TestBed.inject(CalendarService);
});
it('should be created', () => {
+119 -67
View File
@@ -1,10 +1,11 @@
import { Injectable } from '@angular/core';
import { Injectable, inject } from '@angular/core';
import { DateRange } from '@angular/material/datepicker';
import Holidays, { HolidaysTypes } from 'date-holidays';
import dayjs from 'dayjs';
import weekOfYear from 'dayjs/plugin/weekOfYear';
import isoWeek from 'dayjs/plugin/isoWeek';
import { CalendarSettingsService } from './calendar-settings-service';
import { DateCacheService } from './date-cache.service';
dayjs.extend(weekOfYear);
dayjs.extend(isoWeek);
@@ -19,6 +20,12 @@ const allTypesOptions: HolidaysTypes.Options = {
providedIn: 'root',
})
export class CalendarService {
private dateCache = inject(DateCacheService);
// Cache for holiday timestamps
private holidayTimestampsCache: Set<number> | null = null;
private holidayCacheYear: number | null = null;
// Get selected dates from current date to the next year
getSelectedDatesFromNow(): SelectedDates {
const holidays = this.getHolidays();
@@ -31,20 +38,31 @@ export class CalendarService {
const holidays = this.getHolidays();
const monthInAYear = CalendarService.monthsInAYearFromNow();
let selectedDates: SelectedDates = new SelectedDates();
// Use DateCacheService to get today's date components
const {
date: todayDate,
month: todayMonth,
year: todayYear,
} = this.dateCache.getTodayComponents();
// Create a Set of holiday timestamps for O(1) lookup instead of O(n)
const holidayTimestamps = new Set(holidays.map((h) => h.getTime()));
for (const weeksInAMonth of monthInAYear) {
for (const daysInAWeek of weeksInAMonth) {
for (const day of daysInAWeek) {
if (day) {
this.setWeekendSelection(day, selectedDates);
if (holidays.some((holiday) => holiday.getTime() === day.getTime())) {
if (holidayTimestamps.has(day.getTime())) {
selectedDates._datesSelected.push(
new SelectedDate(DayType.CLOSED_DAY, new DateRange<Date>(day, day)),
);
}
if (
day.getDate() === new Date().getDate() &&
day.getMonth() === new Date().getMonth() &&
day.getFullYear() === new Date().getFullYear()
day.getDate() === todayDate &&
day.getMonth() === todayMonth &&
day.getFullYear() === todayYear
) {
selectedDates._datesSelected.push(
new SelectedDate(DayType.TODAY, new DateRange<Date>(day, day)),
@@ -84,12 +102,24 @@ export class CalendarService {
}
getHolidays(): Date[] {
// Cache holidays to avoid recalculation
const currentYear = this.dateCache.getCurrentYear();
if (this.holidayCacheYear === currentYear && this.holidayTimestampsCache) {
// Return timestamps directly for efficient lookup
return Array.from(this.holidayTimestampsCache).map((ts) => new Date(ts));
}
// Logic to return holidays for the given year
const hd = new Holidays('FR', allTypesOptions);
const holidays = hd.getHolidays(new Date().getFullYear(), lang);
const holidaysPlusOne = hd.getHolidays(new Date().getFullYear() + 1, lang);
const holidays = hd.getHolidays(currentYear, lang);
const holidaysPlusOne = hd.getHolidays(currentYear + 1, lang);
holidays.push(...holidaysPlusOne);
let holidaysDate: Date[] = holidays.map((holiday) => new Date(holiday.date));
const holidaysDate: Date[] = holidays.map((holiday) => new Date(holiday.date));
// Update cache
this.holidayTimestampsCache = new Set(holidaysDate.map((d) => d.getTime()));
this.holidayCacheYear = currentYear;
return holidaysDate;
}
@@ -138,9 +168,10 @@ export class CalendarService {
}
static monthsInAYearFromNow(): Year {
const dateCache = inject(DateCacheService);
const months: Year = [];
const currentMonthIndex = new Date().getMonth();
const currentYear = new Date().getFullYear();
const currentMonthIndex = dateCache.getCurrentMonth();
const currentYear = dateCache.getCurrentYear();
for (let i = 0; i < 12; i++) {
const monthIndex = (currentMonthIndex + i) % 12;
const year = currentYear + Math.floor((currentMonthIndex + i) / 12);
@@ -266,6 +297,9 @@ export class SelectedDates implements SelectedDateInterface {
private minDate: Date | null = null;
private maxDate: Date | null = null;
// Constant to indicate no valid strategy was found
private static readonly NO_VALID_STRATEGY_HEURISTIC = -1;
update(): void {
this.datesSelected = this._datesSelected.slice();
this.grouping();
@@ -449,7 +483,7 @@ export class SelectedDates implements SelectedDateInterface {
const current = sorted[i];
const next = sorted[i + 1];
// Get dates as UTC strings to remove timezone issues
// Get dates as UTC strings to remove timezone issues (handles DST properly)
const currentEndDate = new Date(current.range.end ?? new Date());
const nextStartDate = new Date(next.range.start ?? new Date());
@@ -509,21 +543,21 @@ export class SelectedDates implements SelectedDateInterface {
if (calendarSettingsService.samediMalin()) this.samediMalin(vacationsNumber);
while (vacationsNumber.cp > 0) {
const result = this.lookForVacation(DayType.CP);
if (result.heuristic === -1) {
if (result.heuristic === SelectedDates.NO_VALID_STRATEGY_HEURISTIC) {
break;
}
vacationsNumber.cp -= 1;
}
while (vacationsNumber.rtt > 0) {
const result = this.lookForVacation(DayType.RTT);
if (result.heuristic === -1) {
if (result.heuristic === SelectedDates.NO_VALID_STRATEGY_HEURISTIC) {
break;
}
vacationsNumber.rtt -= 1;
}
while (vacationsNumber.other > 0) {
const result = this.lookForVacation(DayType.OTHER);
if (result.heuristic === -1) {
if (result.heuristic === SelectedDates.NO_VALID_STRATEGY_HEURISTIC) {
break;
}
vacationsNumber.other -= 1;
@@ -533,8 +567,9 @@ export class SelectedDates implements SelectedDateInterface {
samediMalin(vacationsNumber: VacationsNumber): void {
const now = new Date();
now.setHours(0, 0, 0, 0);
const nowTime = now.getTime();
const samedi_ferie = this.datesSelected.filter(
const samedi_ferie = this._datesSelected.filter(
(date) => date.type === DayType.CLOSED_DAY && date.range.start?.getDay() === 6,
);
@@ -572,17 +607,17 @@ export class SelectedDates implements SelectedDateInterface {
// Check if we can apply each strategy (and not in the past)
const canApplyTwoBeforeStrategy =
twoDaysBefore1 >= now &&
twoDaysBefore1.getTime() >= nowTime &&
!this.isSelected(twoDaysBefore1) &&
!this.isSelected(twoDaysBefore2);
const canApplyTwoAfterStrategy =
twoDaysAfter1 >= now &&
twoDaysAfter1.getTime() >= nowTime &&
!this.isSelected(twoDaysAfter1) &&
!this.isSelected(twoDaysAfter2);
const canApplyMixedStrategy =
oneDayBefore >= now &&
oneDayBefore.getTime() >= nowTime &&
!this.isSelected(oneDayBefore) &&
!this.isSelected(oneDayAfter);
@@ -597,6 +632,7 @@ export class SelectedDates implements SelectedDateInterface {
new DateRange<Date>(twoDaysBefore1, twoDaysBefore2),
),
);
const heuristic = this.computeHeuristics();
strategies.push({
apply: () => {
this._datesSelected = [...tempDatesBackup];
@@ -609,7 +645,7 @@ export class SelectedDates implements SelectedDateInterface {
vacationsNumber.cp -= 2;
vacationsNumber.other += 1; // Reward: gain 1 other day
},
heuristic: this.computeHeuristics(),
heuristic: heuristic,
});
this._datesSelected = [...tempDatesBackup];
this.datesSelected = this._datesSelected.slice();
@@ -620,6 +656,7 @@ export class SelectedDates implements SelectedDateInterface {
this.push(
new SelectedDate(DayType.CP, new DateRange<Date>(twoDaysAfter1, twoDaysAfter2)),
);
const heuristic = this.computeHeuristics();
strategies.push({
apply: () => {
this._datesSelected = [...tempDatesBackup];
@@ -632,7 +669,7 @@ export class SelectedDates implements SelectedDateInterface {
vacationsNumber.cp -= 2;
vacationsNumber.other += 1; // Reward: gain 1 other day
},
heuristic: this.computeHeuristics(),
heuristic: heuristic,
});
this._datesSelected = [...tempDatesBackup];
this.datesSelected = this._datesSelected.slice();
@@ -646,6 +683,7 @@ export class SelectedDates implements SelectedDateInterface {
this.push(
new SelectedDate(DayType.CP, new DateRange<Date>(oneDayAfter, oneDayAfter)),
);
const heuristic = this.computeHeuristics();
strategies.push({
apply: () => {
this._datesSelected = [...tempDatesBackup];
@@ -664,7 +702,7 @@ export class SelectedDates implements SelectedDateInterface {
vacationsNumber.cp -= 2;
vacationsNumber.other += 1; // Reward: gain 1 other day
},
heuristic: this.computeHeuristics(),
heuristic: heuristic,
});
this._datesSelected = [...tempDatesBackup];
this.datesSelected = this._datesSelected.slice();
@@ -685,61 +723,75 @@ export class SelectedDates implements SelectedDateInterface {
const daysOfYear = CalendarService.monthsInAYearFromNow();
const now = new Date();
now.setHours(0, 0, 0, 0);
daysOfYear.forEach((month) => {
month.forEach((week) => {
week.forEach((day) => {
if (day) {
if (day) day.setHours(0, 0, 0, 0);
if (day && day < now) {
week[week.indexOf(day)] = null;
}
}
});
});
});
const tempDatesBackup = [...this._datesSelected];
let strategies: { apply: () => void; heuristic: number; value: Date }[] = [];
const nowTime = now.getTime();
// Preprocess: filter out past days and already selected days in one pass
const candidateDays: Date[] = [];
for (const month of daysOfYear) {
for (const week of month) {
for (const day of week) {
if (day && !this.isSelected(day)) {
this._datesSelected = [...tempDatesBackup];
this.datesSelected = this._datesSelected.slice();
this.grouping();
// mark these days as vacation
const startDay = new Date(day);
const endDay = new Date(day);
this.datesSelected.push(
new SelectedDate(vacType, new DateRange<Date>(startDay, endDay)),
);
strategies.push({
apply: () => {
this._datesSelected = [...tempDatesBackup];
this.push(
new SelectedDate(
vacType,
new DateRange<Date>(startDay, endDay),
),
);
},
heuristic: this.computeHeuristics(),
value: startDay,
});
this._datesSelected = [...tempDatesBackup];
this.datesSelected = this._datesSelected.slice();
this.grouping();
if (day) {
day.setHours(0, 0, 0, 0);
if (day.getTime() >= nowTime && !this.isSelected(day)) {
candidateDays.push(day);
}
}
}
}
}
// Apply the strategy with the best heuristic score
if (strategies.length > 0) {
const bestStrategy = strategies.reduce((best, current) =>
current.heuristic > best.heuristic ? current : best,
);
// Early exit if no candidates
if (candidateDays.length === 0) {
return { apply: () => {}, heuristic: SelectedDates.NO_VALID_STRATEGY_HEURISTIC };
}
const tempDatesBackup = [...this._datesSelected];
let bestStrategy: { apply: () => void; heuristic: number; value: Date } | null = null;
let bestHeuristic = -Infinity;
// Evaluate each candidate day
for (const day of candidateDays) {
// Reset to backup state
this._datesSelected = [...tempDatesBackup];
this.datesSelected = this._datesSelected.slice();
this.grouping();
// Mark this day as vacation (reuse the day object since it's already normalized)
this.datesSelected.push(new SelectedDate(vacType, new DateRange<Date>(day, day)));
const heuristic = this.computeHeuristics();
// Track only if better than current best
if (heuristic > bestHeuristic) {
bestHeuristic = heuristic;
const capturedDay = day;
bestStrategy = {
apply: () => {
this._datesSelected = [...tempDatesBackup];
this.push(
new SelectedDate(
vacType,
new DateRange<Date>(capturedDay, capturedDay),
),
);
},
heuristic: heuristic,
value: capturedDay,
};
}
}
// Restore backup before returning
this._datesSelected = [...tempDatesBackup];
this.datesSelected = this._datesSelected.slice();
this.grouping();
// Apply best strategy if found
if (bestStrategy) {
bestStrategy.apply();
return bestStrategy;
}
return { apply: () => {}, heuristic: -1 };
return { apply: () => {}, heuristic: SelectedDates.NO_VALID_STRATEGY_HEURISTIC };
}
}
@@ -0,0 +1,46 @@
import { TestBed } from '@angular/core/testing';
import { DateCacheService } from './date-cache.service';
describe('DateCacheService', () => {
let service: DateCacheService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(DateCacheService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
it('should cache today date', () => {
const today1 = service.getToday();
const today2 = service.getToday();
expect(today1).toBe(today2); // Same reference
});
it('should cache today components', () => {
const components1 = service.getTodayComponents();
const components2 = service.getTodayComponents();
expect(components1).toBe(components2); // Same reference
});
it('should cache current month', () => {
const month1 = service.getCurrentMonth();
const month2 = service.getCurrentMonth();
expect(month1).toBe(month2);
});
it('should cache current year', () => {
const year1 = service.getCurrentYear();
const year2 = service.getCurrentYear();
expect(year1).toBe(year2);
});
it('should clear cache', () => {
const year1 = service.getCurrentYear();
service.clearCache();
const year2 = service.getCurrentYear();
expect(year1).toBe(year2); // Values should be the same even after clearing
});
});
+105
View File
@@ -0,0 +1,105 @@
import { Injectable } from '@angular/core';
/**
* Service to cache and provide commonly used date values.
* This reduces redundant Date object creation across the application.
*/
@Injectable({
providedIn: 'root',
})
export class DateCacheService {
private _today: Date | null = null;
private _todayComponents: { date: number; month: number; year: number } | null = null;
private _currentMonth: number | null = null;
private _currentYear: number | null = null;
/**
* Get today's date (time set to 00:00:00.000)
*/
getToday(): Date {
if (!this._today || this.isNewDay(this._today)) {
this._today = new Date();
this._today.setHours(0, 0, 0, 0);
this._todayComponents = null; // Invalidate components cache
}
return this._today;
}
/**
* Get today's date components (date, month, year) for efficient comparison
*/
getTodayComponents(): { date: number; month: number; year: number } {
if (!this._todayComponents || (this._today && this.isNewDay(this._today))) {
const today = this.getToday();
this._todayComponents = {
date: today.getDate(),
month: today.getMonth(),
year: today.getFullYear(),
};
}
return this._todayComponents;
}
/**
* Get current month (0-11)
*/
getCurrentMonth(): number {
if (this._currentMonth === null || this.isNewMonth()) {
this._currentMonth = new Date().getMonth();
}
return this._currentMonth;
}
/**
* Get current year
*/
getCurrentYear(): number {
if (this._currentYear === null || this.isNewYear()) {
this._currentYear = new Date().getFullYear();
}
return this._currentYear;
}
/**
* Get current date with time set to 00:00:00.000 (alias for getToday)
*/
getNow(): Date {
return this.getToday();
}
/**
* Check if a cached date is from a previous day
*/
private isNewDay(cachedDate: Date): boolean {
const now = new Date();
return (
cachedDate.getDate() !== now.getDate() ||
cachedDate.getMonth() !== now.getMonth() ||
cachedDate.getFullYear() !== now.getFullYear()
);
}
/**
* Check if we're in a new month
*/
private isNewMonth(): boolean {
return this._currentMonth !== null && this._currentMonth !== new Date().getMonth();
}
/**
* Check if we're in a new year
*/
private isNewYear(): boolean {
return this._currentYear !== null && this._currentYear !== new Date().getFullYear();
}
/**
* Clear all caches (useful for testing)
*/
clearCache(): void {
this._today = null;
this._todayComponents = null;
this._currentMonth = null;
this._currentYear = null;
}
}