Skip to main content

calendarDaysNeed

/**
* Calculates the end date of a task based on a start date, number of days to complete, and a list of holidays.
* @param {*} startDate
* @param {*} daysToComplete
* @param {*} holidays
* @returns
*/
function calculateEndDate(startDate, daysToComplete, holidays = []) {
// Normalize holidays to a comparable string form for O(1) lookup.
const holidaySets = new Set(
holidays.map((date) => new Date(date).toDateString())
);

let current = new Date(startDate);
let workdaysCompeleted = 0;

// Move day-by-day until we finish the required number of working days.
while (workdaysCompeleted < daysToComplete) {
const day = current.getDay(); // index where 0 is Sun, 6 = Sat
const isWeekend = day === 0 || day === 6;
const isHoliday = holidaySets.has(current.toDateString());

// Count only business days (not weekend, not holiday).
if (!isWeekend && !isHoliday) {
workdaysCompeleted++;
}

// Stop on the exact completion date; otherwise continue to next day.
if (workdaysCompeleted < daysToComplete) {
current.setDate(current.getDate() + 1);
}
}

// Version 1 output: return the actual completion Date.
return current;
}

const endDate = calculateEndDate(
"2026-07-01", // startDate
5,
["2026-07-03"]
);

console.log(endDate.toDateString()); // this will return the date

function calculateCalendarDaysNeeded(startDate, daysToComplete, holidays = []) {
// Same business-day logic as calculateEndDate, but different output.
const holidaySets = new Set(
holidays.map(date => new Date(date).toDateString())
);

let current = new Date(startDate);
let workdaysCompeleted = 0;
let calendarDays = 0;

while(workdaysCompeleted < daysToComplete) {
const day = current.getDay();
const isWeekend = day === 0 || day === 6;
const isHoliday = holidaySets.has(current.toDateString());

if (!isWeekend && !isHoliday) {
workdaysCompeleted++;
}

// Count every traversed day, including weekends/holidays.
calendarDays++;

if (workdaysCompeleted < daysToComplete) {
current.setDate(current.getDate() + 1);
}
}

// Version 2 output: total calendar days needed to complete the work.
return calendarDays;
}

console.log(
calculateCalendarDaysNeeded("2026-07-01", 5, ["2026-07-03"])
);