@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.
199 lines (197 loc) • 9.45 kB
JavaScript
import { Temporal } from "./temporal.js";
import { isValidDate } from "../plain/validate/isValidDate.js";
import { isValidTimeZone } from "../zoned/validate/isValidTimeZone.js";
import { isObject } from "./isObject.js";
import { ISO_WEEKDAYS, MAX_EPOCH_DAY, MIN_EPOCH_DAY, countWithin, epochDayOfDate, hasEpochDay, isoFieldsOf, isoWeekdayOf, sortedUnique } from "./epochDay.js";
// src/internal/businessCalendar.ts
/**
* The weekend GMT assumed before calendars existed: Saturday and Sunday, no holidays. It is
* what `isBusinessDay`, `addBusinessDays` and `subtractBusinessDays` use when no calendar is
* passed, so their shipped behaviour is unchanged.
*/
const DEFAULT_WEEKEND = [6, 7];
/**
* Calendar days a single business-day walk may step before giving up — roughly 547 years, far
* past any real schedule. A walk that runs out returns the sentinel, never a partial answer.
*/
const MAX_BUSINESS_DAY_STEPS = 2e5;
/** Shared by every caller without a calendar: its arrays are empty and never mutated. */
const DEFAULT_BUSINESS_CALENDAR = {
weekend: new Set(DEFAULT_WEEKEND),
holidays: /* @__PURE__ */ new Int32Array(0),
closures: /* @__PURE__ */ new Int32Array(0)
};
function parseWeekend(weekend) {
if (!Array.isArray(weekend)) return null;
if (!weekend.every((day) => Number.isInteger(day) && day >= 1 && day <= 7)) return null;
const days = new Set(weekend);
return days.size < 7 ? days : null;
}
/** Most raw holiday strings the memo keeps before it starts over. */
const HOLIDAY_MEMO_LIMIT = 65536;
/**
* Raw holiday string to its epoch day. Only valid strings are stored: `isValidDate` and
* `PlainDate.from` on an ISO string are pure functions of the string, so a hit is always
* right and clearing the map costs speed, never correctness.
*/
const holidayMemo = /* @__PURE__ */ new Map();
/** Empty the holiday memo. Tests only. */
function clearHolidayMemo() {
holidayMemo.clear();
}
/** The epoch day of an ISO holiday string, or `null` when it is not one. */
function holidayEpochDay(holiday) {
if (typeof holiday !== "string") return null;
const known = holidayMemo.get(holiday);
if (known !== void 0) return known;
if (!isValidDate(holiday)) return null;
const epochDay = epochDayOfDate(Temporal.PlainDate.from(holiday));
if (holidayMemo.size >= HOLIDAY_MEMO_LIMIT) holidayMemo.clear();
holidayMemo.set(holiday, epochDay);
return epochDay;
}
/**
* Reduce a holiday list to its epoch days, sorted ascending without repeats, or `null` when it
* is not an array of ISO PlainDate strings. Shared with `OperatingSchedule.holidays`, which
* takes the same list.
*/
function parseHolidays(holidays) {
if (!Array.isArray(holidays)) return null;
const days = [];
try {
for (let index = 0; index < holidays.length; index++) {
const epochDay = holidayEpochDay(holidays[index]);
if (epochDay === null) return null;
days.push(epochDay);
}
} catch {
return null;
}
return sortedUnique(Int32Array.from(days));
}
/**
* Reduce a caller-supplied `BusinessCalendar` to its lookups, or `null` when it is not one.
*
* `undefined` is rejected here; `resolveBusinessCalendar` is the entry point that treats an
* absent calendar as the default Saturday–Sunday week.
*/
function parseBusinessCalendar(calendar) {
if (!isObject(calendar) || Array.isArray(calendar)) return null;
const { weekend, holidays, timeZone } = calendar;
if (typeof timeZone !== "string" || !isValidTimeZone(timeZone)) return null;
const weekendDays = parseWeekend(weekend);
const holidayDates = parseHolidays(holidays);
if (weekendDays === null || holidayDates === null) return null;
return resolveParts(weekendDays, holidayDates);
}
/**
* Join a parsed weekend and a sorted, repeat-free holiday list into the lookups every walk
* needs, filtering out the holidays that fall on a weekend day.
*/
function resolveParts(weekend, holidays) {
return {
weekend,
holidays,
closures: holidays.filter((day) => !weekend.has(isoWeekdayOf(day)))
};
}
/**
* Resolve an optional calendar: absent means the default Saturday–Sunday week with no
* holidays, anything else must be a valid `BusinessCalendar` or this returns `null`.
*/
function resolveBusinessCalendar(calendar) {
return calendar === void 0 ? DEFAULT_BUSINESS_CALENDAR : parseBusinessCalendar(calendar);
}
/**
* True when `date` is neither a weekend day nor a holiday in `calendar`. `date` must be an
* ISO-calendar date: any other calendar throws a `RangeError`. Every caller passes a date it
* parsed from an ISO string or took from `toPlainDate()` of a zoned string parsed the same way.
*/
function isBusinessDate(date, calendar) {
return isBusinessEpochDay(epochDayOfDate(date), calendar);
}
/** True when `epochDay` is neither a weekend day nor a holiday on a working weekday. */
function isBusinessEpochDay(epochDay, calendar) {
return !calendar.weekend.has(isoWeekdayOf(epochDay)) && !hasEpochDay(calendar.closures, epochDay);
}
/** Business days in [from, to] (epoch days, from <= to); 0 when from > to. */
function businessDaysWithin(from, to, calendar) {
if (from > to) return 0;
const days = to - from + 1;
const wholeWeeks = Math.floor(days / 7);
let count = wholeWeeks * (7 - calendar.weekend.size);
for (let day = from + wholeWeeks * 7; day <= to; day++) if (!calendar.weekend.has(isoWeekdayOf(day))) count += 1;
return count - countWithin(calendar.closures, from, to);
}
/** The walked-to date; `date` itself when the walk never moved. */
function dateAt(date, startEpochDay, epochDay) {
if (epochDay === startEpochDay) return date;
const [year, month, day] = isoFieldsOf(epochDay);
return new Temporal.PlainDate(year, month, day);
}
/** Business days among the days `fromOffset` to `toOffset` away from `start` in `direction`. */
function businessDaysInOffsetRange(start, direction, fromOffset, toOffset, calendar) {
return direction === 1 ? businessDaysWithin(start + fromOffset, start + toOffset, calendar) : businessDaysWithin(start - toOffset, start - fromOffset, calendar);
}
/**
* The smallest distance `k` from `start`, at least `firstOffset`, whose span of days
* `firstOffset`..`k` holds `target` business days; the walk reaches at most `MAX_BUSINESS_DAY_STEPS`
* days out. Gives up as the day-by-day walk did: a `RangeError` when it would have stepped past a
* Temporal limit first, `null` when it ran out of steps.
*/
function distanceToNthBusinessDay(start, direction, firstOffset, target, calendar) {
const limitDistance = direction === 1 ? MAX_EPOCH_DAY - start : start - MIN_EPOCH_DAY;
const lastOffset = Math.min(MAX_BUSINESS_DAY_STEPS, limitDistance);
if (businessDaysInOffsetRange(start, direction, firstOffset, lastOffset, calendar) < target) {
if (2e5 > limitDistance) throw new RangeError("date/time value is outside of supported range");
return null;
}
let low = firstOffset;
let high = lastOffset;
while (low < high) {
const middle = Math.floor((low + high) / 2);
if (businessDaysInOffsetRange(start, direction, firstOffset, middle, calendar) >= target) high = middle;
else low = middle + 1;
}
return low;
}
/**
* The first business day at or beyond `date`, walking in `direction`.
*
* `date` is an ISO-calendar date, as every caller validates. Returns `date` itself when it is
* already a business day, and `null` when the walk exceeds `MAX_BUSINESS_DAY_STEPS`. Throws a
* `RangeError` when the walk passes a Temporal range limit.
*/
function businessDateFrom(date, direction, calendar) {
const start = epochDayOfDate(date);
const distance = distanceToNthBusinessDay(start, direction, 0, 1, calendar);
return distance === null ? null : dateAt(date, start, start + direction * distance);
}
/**
* First business day strictly after `epochDay`: the epoch-day form of `stepBusinessDates` with
* a count of 1, so no `PlainDate` is built. Returns `null` when the walk exceeds
* `MAX_BUSINESS_DAY_STEPS`; throws a `RangeError` when it passes a Temporal range limit.
*/
function nextBusinessEpochDay(epochDay, calendar) {
const distance = distanceToNthBusinessDay(epochDay, 1, 1, 1, calendar);
return distance === null ? null : epochDay + distance;
}
/**
* Step `count` business days from `date` in `direction`, counting only days that are business
* days in `calendar`.
*
* `date` is an ISO-calendar date, as every caller validates. `date` itself is never counted, so
* a `count` of 0 returns `date` unchanged even when it is not a business day. Returns `null`
* when the walk exceeds `MAX_BUSINESS_DAY_STEPS`, and for a `count` that is not a whole number
* of days or is negative or NaN: a fractional or infinite `count` still walks first, as the
* day-by-day loop did, so it throws the same `RangeError` when it passes a Temporal range limit
* before finishing. Throws a `RangeError` when any walk passes a Temporal range limit.
*/
function stepBusinessDates(date, direction, count, calendar) {
const start = epochDayOfDate(date);
if (count === 0) return date;
if (!(count > 0)) return null;
const distance = distanceToNthBusinessDay(start, direction, 1, Math.ceil(count), calendar);
return distance === null || !Number.isInteger(count) ? null : dateAt(date, start, start + direction * distance);
}
export { DEFAULT_BUSINESS_CALENDAR, MAX_BUSINESS_DAY_STEPS, businessDateFrom, businessDaysWithin, clearHolidayMemo, holidayEpochDay, isBusinessDate, isBusinessEpochDay, nextBusinessEpochDay, parseBusinessCalendar, parseHolidays, parseWeekend, resolveBusinessCalendar, resolveParts, stepBusinessDates };