MCPcopy
hub / github.com/date-fns/date-fns / tpyAddBusinessDays

Function tpyAddBusinessDays

pkgs/core/src/addBusinessDays/index.tp.ts:9–52  ·  view source on GitHub ↗
(
  date: DateArg<DateType>,
  amount: number,
  options?: AddBusinessDaysOptions<ResultDate> | undefined,
)

Source from the content-addressed store, hash-verified

7import type { AddBusinessDaysOptions } from "./index.ts";
8
9export function tpyAddBusinessDays<
10 DateType extends Date,
11 ResultDate extends Date = DateType,
12>(
13 date: DateArg<DateType>,
14 amount: number,
15 options?: AddBusinessDaysOptions<ResultDate> | undefined,
16): ResultDate {
17 let [temporal, invalidDate] = toTpInstant(date, options);
18 if (!temporal || isNaN(amount)) return invalidDate;
19
20 const startedOnWeekend = tpIsWeekend(temporal);
21 const hours = temporal.hour;
22 const sign = amount < 0 ? -1 : 1;
23 const fullWeeks = Math.trunc(amount / 5);
24
25 temporal = temporal.add({ days: fullWeeks * 7 });
26
27 // Get remaining days not part of a full week
28 let restDays = Math.abs(amount % 5);
29
30 // Loops over remaining days
31 while (restDays > 0) {
32 temporal = temporal.add({ days: sign });
33 if (!tpIsWeekend(temporal)) restDays -= 1;
34 }
35
36 // If the date is a weekend day and we reduce a dividable of
37 // 5 from it, we land on a weekend date.
38 // To counter this, we add days accordingly to land on the next business day
39 if (startedOnWeekend && tpIsWeekend(temporal) && amount !== 0) {
40 // If we're reducing days, we want to add days until we land on a weekday
41 // If we're adding days we want to reduce days until we land on a weekday
42 if (tpIsSaturday(temporal))
43 temporal = temporal.add({ days: sign < 0 ? 2 : -1 });
44 if (tpIsSunday(temporal))
45 temporal = temporal.add({ days: sign < 0 ? 1 : -2 });
46 }
47
48 // Restore hours to avoid DST lag
49 temporal = temporal.with({ hour: hours });
50
51 return constructFrom(options?.in || date, temporal.epochMilliseconds);
52}

Callers

nothing calls this directly

Calls 5

toTpInstantFunction · 0.90
tpIsWeekendFunction · 0.90
tpIsSaturdayFunction · 0.90
tpIsSundayFunction · 0.90
constructFromFunction · 0.90

Tested by

no test coverage detected