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.

56 lines (54 loc) • 2.68 kB
import { isObject } from "./isObject.js"; import { ISO_WEEKDAYS, MAX_EPOCH_DAY, MIN_EPOCH_DAY, isoWeekdayOf } from "./epochDay.js"; import { nextBusinessEpochDay } from "./businessCalendar.js"; import { isValidDayOfWeek } from "./isValidDayOfWeek.js"; // src/internal/observance.ts /** The `next` or `previous` key of a one-key shift object, or `null` for any other shape. */ function shiftDirection(value) { const keys = isObject(value) && !Array.isArray(value) ? Object.keys(value) : []; return keys.length === 1 && (keys[0] === "next" || keys[0] === "previous") ? keys[0] : null; } /** One shift, or `null` when it is not `"nextWorkingDay"`, `{ next: d }` or `{ previous: d }` with `d` another weekday. */ function parseShift(value, weekday) { if (value === "nextWorkingDay") return value; const direction = shiftDirection(value); const target = direction === null ? null : value[direction]; if (typeof target !== "number" || !isValidDayOfWeek(target) || target === weekday) return null; return { [direction]: target }; } /** * Reduce a caller-supplied `ObservancePolicy` to a weekday-indexed table, or `null` when it is * not one: keys must be `"1"`..`"7"` and each value a valid shift. */ function parseObservancePolicy(policy) { if (!isObject(policy) || Array.isArray(policy)) return null; const resolved = Array.from({ length: 7 + 1 }, () => void 0); for (const key of Object.keys(policy)) { const weekday = Number(key); if (!isValidDayOfWeek(weekday) || String(weekday) !== key) return null; const shift = parseShift(policy[key], weekday); if (shift === null) return null; resolved[weekday] = shift; } return resolved; } /** True when some weekday shifts to `"nextWorkingDay"`, which cannot be answered without a calendar. */ function policyNeedsCalendar(policy) { return policy.includes("nextWorkingDay"); } /** * Observed epoch day, the same day when no shift applies, or `null` (out of range, no calendar, * walk failed). `{ next: d }` moves 1..6 days later, `{ previous: d }` 1..6 days earlier. Throws * a `RangeError` when a `nextWorkingDay` walk passes Temporal's range. */ function observedEpochDay(day, policy, calendar) { const shift = policy[isoWeekdayOf(day)]; let result = day; if (shift === "nextWorkingDay") result = calendar === null ? null : nextBusinessEpochDay(day, calendar); else if (shift !== void 0) { const weekday = isoWeekdayOf(day); result = "next" in shift ? day + ((shift.next - weekday + 6) % 7 + 1) : day - ((weekday - shift.previous + 6) % 7 + 1); } return result === null || result < -100000001 || result > 1e8 ? null : result; } export { observedEpochDay, parseObservancePolicy, policyNeedsCalendar };