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.

51 lines (49 loc) • 2.56 kB
import { MAX_EPOCH_NANOSECONDS, MIN_EPOCH_NANOSECONDS } from "../epochNanoseconds.js"; import { isNamedTimeZone } from "../zonedWallClock.js"; import { NANOSECONDS_PER_DAY, NANOSECONDS_PER_TIME_UNIT, bigintAbs, toInternalDuration } from "./operations.js"; import { checkUtcValidity } from "./utcValidity.js"; // src/internal/zonedDifference/rangeLimit.ts /** Upper bound on one unit's exact length in any zone: 366-day years, 31-day months, 2-day days. */ const UNIT_REACH = { year: 366n * NANOSECONDS_PER_DAY, month: 31n * NANOSECONDS_PER_DAY, week: 7n * NANOSECONDS_PER_DAY, day: 2n * NANOSECONDS_PER_DAY, ...NANOSECONDS_PER_TIME_UNIT }; /** A wall clock lies within a day of its exact time, and the offset probes look one day further. */ const LIMIT_MARGIN = 2n * NANOSECONDS_PER_DAY; /** True when `epochs`, widened by `reach` and the limit margin, touch either range limit. */ function reachesRangeLimit(epochs, reach) { const widen = reach + LIMIT_MARGIN; return epochs.some((epoch) => epoch - widen <= -8640000000000000000000n || epoch + widen >= 8640000000000000000000n); } /** An upper bound on how far `duration` moves an exact time in any zone. */ function durationReach(duration) { const { date, time } = toInternalDuration(duration); return BigInt(Math.abs(date.years)) * UNIT_REACH.year + BigInt(Math.abs(date.months)) * UNIT_REACH.month + BigInt(Math.abs(date.weeks)) * UNIT_REACH.week + BigInt(Math.abs(date.days)) * UNIT_REACH.day + bigintAbs(time); } /** How far rounding can look past its destination: one increment, then bubbling to `largestUnit`. */ function roundingReach(settings) { const increment = Number.isSafeInteger(settings.increment) ? Math.abs(settings.increment) : 1; return UNIT_REACH[settings.largestUnit] + BigInt(Math.max(increment, 1)) * UNIT_REACH[settings.smallestUnit]; } /** * Returns `compute(timeZone)`, the polyfill's own result, unchanged. Near a range limit only: * a UTC result is checked with `checkUtcValidity` (defect 2), and a named zone's error is * replaced by `fallback`'s TC39 result when it has one (defect 1). */ function runAtRangeLimit(timeZone, atRangeLimit, compute, fallback) { let result; try { result = compute(timeZone); } catch (error) { if (!atRangeLimit || !isNamedTimeZone(timeZone)) throw error; const recovered = fallback(); if (recovered === null) throw error; return recovered; } if (atRangeLimit && timeZone === "UTC") checkUtcValidity(compute); return result; } export { UNIT_REACH, durationReach, reachesRangeLimit, roundingReach, runAtRangeLimit };