UNPKG

@northguild/gmt

Version:

Date and time library for JavaScript and TypeScript, built on TC39 Temporal: time zones, DST, business days, ISO 8601 strings in and out. Never throws.

37 lines (35 loc) • 1.52 kB
import { businessDateFrom } from "./businessCalendar.js"; // src/internal/rollBusinessDate.ts function sameMonth(a, b) { return a.year === b.year && a.month === b.month; } /** * Roll in `direction`, and if that leaves the date's month, roll the other way instead. */ function modifiedRoll(date, direction, calendar) { const rolled = businessDateFrom(date, direction, calendar); if (rolled === null) return null; return sameMonth(rolled, date) ? rolled : businessDateFrom(date, direction === 1 ? -1 : 1, calendar); } /** * Move a date onto a working day according to `convention`, over an already-parsed calendar. * The core of `rollDate` and `cutoffAt`; neither calls the other. * * @param date the date to roll * @param convention the roll convention, already validated * @param calendar the parsed business calendar * @returns the rolled date, or `null` when the walk runs out * * @example rollBusinessDate(Temporal.PlainDate.from("2024-06-01"), "following", calendar) // 2024-06-03 (Saturday to Monday) */ function rollBusinessDate(date, convention, calendar) { switch (convention) { case "following": return businessDateFrom(date, 1, calendar); case "preceding": return businessDateFrom(date, -1, calendar); case "modifiedFollowing": return modifiedRoll(date, 1, calendar); case "modifiedPreceding": return modifiedRoll(date, -1, calendar); case "endOfMonth": return businessDateFrom(date.with({ day: date.daysInMonth }), -1, calendar); case "none": return date; } } export { rollBusinessDate };