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.39 kB
import { ISO_WEEKDAYS, MAX_EPOCH_DAY, MIN_EPOCH_DAY, epochDayOf, isoWeekdayOf } from "./epochDay.js"; // src/internal/nthWeekday.ts const ORDINALS = /* @__PURE__ */ new Set([ 1, 2, 3, 4, 5, -1, -2, -3, -4, -5, "last" ]); /** True for `1..5`, `-1..-5` and `"last"`: the ordinals RFC 5545 §3.3.10 allows in a monthly `BYDAY`, plus the `"last"` alias. */ function isWeekdayOrdinal(value) { return ORDINALS.has(value); } /** The signed integer an ordinal stands for: `"last"` is `-1` (GMT's readable alias for the RFC 5545 ordinal). */ function ordinalNumber(n) { return n === "last" ? -1 : n; } /** * Epoch day of the `n`-th ISO `weekday` in the closed day range `[first, last]` (epoch days): * `n > 0` counts from `first`, `n < 0` from `last`. `null` when that occurrence lies outside the * range. The range may reach past Temporal's date range and the count includes those days: a * recurrence period counts its whole span before it drops the dates a PlainDate cannot hold. * `n` is a nonzero integer. Closed form: the offset to the first (or last) matching weekday plus * `7 x (|n| - 1)`, no loop. */ function nthWeekdayWithin(first, last, weekday, n) { const day = n > 0 ? first + (weekday - isoWeekdayOf(first) + 7) % 7 + 7 * (n - 1) : last - (isoWeekdayOf(last) - weekday + 7) % 7 - 7 * (-n - 1); return day >= first && day <= last ? day : null; } /** * Epoch day of the `n`-th ISO `weekday` in the closed day range `[first, last]` (epoch days), or * `null` when that occurrence lies outside the range or outside Temporal's date range. See * {@link nthWeekdayWithin} for the count. */ function nthWeekdayInRange(first, last, weekday, n) { const day = nthWeekdayWithin(first, last, weekday, n); return day !== null && day >= -100000001 && day <= 1e8 ? day : null; } /** * Epoch day of the `n`-th ISO weekday of an ISO month, or `null` when that occurrence does not * exist or lies outside Temporal's date range. `n` is an already-checked integer in * `-5..-1` or `1..5`. Counts from the month's first day (`n > 0`) or last day (`n < 0`). */ function nthWeekdayEpochDay(year, month, weekday, n) { const next = month === 12 ? epochDayOf(year + 1, 1, 1) : epochDayOf(year, month + 1, 1); return nthWeekdayInRange(epochDayOf(year, month, 1), next - 1, weekday, n); } export { isWeekdayOrdinal, nthWeekdayEpochDay, nthWeekdayInRange, nthWeekdayWithin, ordinalNumber };