I am currently developing a calendar application using ExpressJS and TypeScript. Within this project, I have implemented a function that manages recurring events and returns an array of events for a specific month upon request.
let response: TEventResponse[] = [];
for (let i = 0; i < events.length; i++) {
let e = events[i];
if (!e.isPeriodical) {
const event: TEventResponse = {
beginning: e.beginTime,
ending: e.endTime,
title: e.title,
description: e.description,
place: e.place,
};
response.push(event);
} else {
let beginning = new Date(e.beginTime);
const upperDate = new Date();
upperDate.setFullYear(year);
upperDate.setMonth(month + 1);
upperDate.setDate(1);
const lowerDate = new Date();
lowerDate.setFullYear(year);
lowerDate.setMonth(month);
lowerDate.setDate(1);
console.log(lowerDate);
console.log(upperDate);
let dateBoundary = undefined;
if (e.dateBoundary) {
dateBoundary = e.dateBoundary;
} else {
dateBoundary = upperDate;
}
console.log(dateBoundary);
if (dateBoundary >= upperDate) {
const periodicalEventsArr: TEventResponse[] = [];
while (beginning <= dateBoundary && beginning < upperDate) {
if (beginning >= lowerDate) {
const event: TEventResponse = {
beginning: beginning,
ending: e.endTime,
title: e.title,
description: e.description,
place: e.place,
};
periodicalEventsArr.push(event);
console.log(periodicalEventsArr);
}
const n = e.repeatPeriod!;
switch (e.repeatPeriodUnit) {
case "DAY":
beginning.setDate(beginning.getDate() + n);
break;
case "WEEK":
beginning.setDate(beginning.getDate() + n * 7);
break;
case "MONTH":
beginning.setMonth(beginning.getMonth() + n);
break;
case "YEAR":
beginning.setFullYear(beginning.getFullYear() + n);
break;
}
console.log(periodicalEventsArr);
}
response.concat(periodicalEventsArr);
}
}
}
return response;
The main for loop functions correctly, but the inner while loop, intended to add a periodic event multiple times by adjusting the date each time, is exhibiting unexpected behavior.
Although the event appears to be added correctly initially (as shown in the first console.log(periodicalEventsArr)
), subsequent iterations are modifying not only the 'beginning' value of the new event but also altering the same field in all previously added events (visible from the second console.log(periodicalEventsArr)
). Consequently, the final array primarily consists of duplicates of the last added event.
This issue has puzzled me for some time now, and I would greatly appreciate any insights or guidance on where I may be going wrong.