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.

262 lines (260 loc) • 10.8 kB
import { calendarFieldsOf, polyfillCannotReturn, polyfillMisreadsIslamicEra } from "./calendarFields.js"; import { floorDateForFields, floorDateForFieldsBetween, isLastRepresentableDate } from "./fieldSearch.js"; import { calendarDateFromFields } from "./calendarDateFromFields.js"; import { addManyMonths, countManyMonths, fixedMonthsPerYearOf, isLargeMonthSpan, isLargeYearSpan } from "./largeMonthSpan.js"; import { addFixedMonths, fixedMonthsBetween } from "./fixedMonthArithmetic.js"; // src/internal/temporalCompat/readArithmeticModel.ts const ISO_CALENDAR = "iso8601"; const LAST = Number.MAX_SAFE_INTEGER; /** Days searched past a month's first day for its last day: more than any calendar month has. */ const MONTH_SEARCH_DAYS = 64; /** * Months stepped one at a time next to a limit. The polyfill's D1 windows reach at most 357 days * from a limit (persian at the minimum), which 14 months always clear. */ const EDGE_WALK_MONTHS = 14; const JUMP_BACKOFF_MONTHS = [ EDGE_WALK_MONTHS, 28, 42 ]; const CACHE_LIMIT = 1024; const MONTH_CODE = /^M(\d{2})(L?)$/; const models = /* @__PURE__ */ new Map(); const lastMonths = /* @__PURE__ */ new Map(); function compareYearMonths(a, b) { return a.year - b.year || a.month - b.month; } function unlessRangeError(run) { try { return run(); } catch (error) { if (error instanceof RangeError) return; throw error; } } function requireMonth(month) { if (month === null) throw new RangeError("Month is outside the representable range"); return month; } /** Day 1 of `month`, calendared; undefined when it does not exist or lies outside the range. */ function monthStart(calendarId, month) { return unlessRangeError(() => calendarDateFromFields(calendarId, { year: month.year, month: month.month, day: 1 }, "reject")); } /** The last ordinal month of `year`, or null when no day of that year is representable. */ function lastMonthOf(calendarId, year) { const key = `${calendarId}/${year}`; const cached = lastMonths.get(key); if (cached !== void 0) return cached; const floor = floorDateForFields(calendarId, { year, month: LAST, day: LAST }); const read = floor === null ? null : calendarFieldsOf(floor, calendarId); const result = floor !== null && read?.year === year ? { month: read.month, complete: !isLastRepresentableDate(floor) } : null; if (lastMonths.size >= CACHE_LIMIT) lastMonths.clear(); lastMonths.set(key, result); return result; } function stepMonth(calendarId, month, sign) { if (sign < 0) { if (month.month > 1) return { year: month.year, month: month.month - 1 }; const previous = lastMonthOf(calendarId, month.year - 1); return previous === null ? null : { year: month.year - 1, month: previous.month }; } const last = lastMonthOf(calendarId, month.year); if (last === null) return null; if (month.month < last.month) return { year: month.year, month: month.month + 1 }; return last.complete ? { year: month.year + 1, month: 1 } : null; } function walkMonths(calendarId, start, months) { const sign = Math.sign(months); let current = start; for (let step = 0; current !== null && step < Math.abs(months); step++) current = stepMonth(calendarId, current, sign); return current; } function polyfillAddMonths(calendarId, start, months) { const origin = monthStart(calendarId, start); if (origin === void 0) return; const moved = unlessRangeError(() => calendarFieldsOf(origin.add({ months }), calendarId)); return moved?.day === 1 ? { year: moved.year, month: moved.month } : void 0; } /** * D18: the months in every year of `calendarId` when the polyfill cannot be asked about some year * (`isAffected` is read only then, so the count is measured only on an affected runtime), else * undefined. A calendar the polyfill cannot answer for has fixed months per year (the Islamic * calendars); a leap-month calendar would have none and so always takes the other paths. */ function fixedMonthsIfPolyfillCannotReturn(calendarId, isAffected) { if (!polyfillMisreadsIslamicEra(calendarId)) return; const perYear = fixedMonthsPerYearOf(calendarId); return perYear !== void 0 && isAffected(perYear) ? perYear : void 0; } function addMonths(calendarId, start, months) { if (months === 0) return start; const perYear = fixedMonthsIfPolyfillCannotReturn(calendarId, (count) => polyfillCannotReturn(calendarId, start.year) || polyfillCannotReturn(calendarId, addFixedMonths(start, months, count).year)); if (perYear !== void 0) { const target = addFixedMonths(start, months, perYear); return monthCodeAt(calendarId, target) === void 0 ? null : target; } if (isLargeMonthSpan(months)) return addManyMonths(calendarId, start, months, (from, count) => addMonths(calendarId, from, count), (from, to) => monthsBetween(calendarId, from, to)); const jumped = polyfillAddMonths(calendarId, start, months); if (jumped !== void 0) return jumped; return addMonthsNearLimit(calendarId, start, months); } /** * Near a limit: leave a month that begins before the range, jump to a month start short of the * limit, and step the rest. */ function addMonthsNearLimit(calendarId, start, months) { const sign = Math.sign(months); let origin = start; let remaining = months; if (monthStart(calendarId, origin) === void 0) { origin = stepMonth(calendarId, origin, sign); remaining -= sign; if (origin === null || remaining === 0) return origin; } for (const backoff of JUMP_BACKOFF_MONTHS) { if (Math.abs(remaining) <= backoff) return walkMonths(calendarId, origin, remaining); const anchor = polyfillAddMonths(calendarId, origin, remaining - sign * backoff); if (anchor !== void 0) return walkMonths(calendarId, anchor, sign * backoff); } throw new RangeError(`Cannot add ${months} months to ${calendarId} ${start.year}-${start.month}`); } function polyfillMonthsBetween(calendarId, from, to) { const start = monthStart(calendarId, from); const end = monthStart(calendarId, to); if (start === void 0 || end === void 0) return; return unlessRangeError(() => start.until(end, { largestUnit: "months" }).months); } function monthsBetween(calendarId, from, to) { const sign = Math.sign(compareYearMonths(to, from)); if (sign === 0) return 0; const perYear = fixedMonthsIfPolyfillCannotReturn(calendarId, () => polyfillCannotReturn(calendarId, from.year) || polyfillCannotReturn(calendarId, to.year)); if (perYear !== void 0) return fixedMonthsBetween(from, to, perYear); if (isLargeYearSpan(from.year, to.year)) return countManyMonths(calendarId, from, to, (one, two) => monthsBetween(calendarId, one, two)); const direct = polyfillMonthsBetween(calendarId, from, to); if (direct !== void 0) return direct; return monthsBetweenNearLimit(calendarId, from, to, sign); } /** * Near a limit: count the months at each end one at a time, and let the polyfill count between * the month starts left in the middle. */ function monthsBetweenNearLimit(calendarId, from, to, sign) { let low = from; let high = to; let count = 0; for (let step = 0; step < EDGE_WALK_MONTHS && compareYearMonths(low, high) !== 0; step++) { low = requireMonth(stepMonth(calendarId, low, sign)); count += sign; } for (let step = 0; step < EDGE_WALK_MONTHS && compareYearMonths(low, high) !== 0; step++) { high = requireMonth(stepMonth(calendarId, high, -sign)); count += sign; } if (compareYearMonths(low, high) === 0) return count; const middle = polyfillMonthsBetween(calendarId, low, high); if (middle === void 0) throw new RangeError(`Cannot count ${calendarId} months from ${from.year}-${from.month} to ${to.year}-${to.month}`); return count + middle; } /** * The latest in-range date at or before the last day of `month`: searched in a window after the * month's first day when that day is readable, with a read-back that the next day starts a new * month (otherwise, and when day 1 is not readable, over the whole range). */ function lastDayFloor(calendarId, month) { const target = { year: month.year, month: month.month, day: LAST }; const start = monthStart(calendarId, month); const windowed = start === void 0 ? null : floorDateForFieldsBetween(calendarId, target, start, MONTH_SEARCH_DAYS); if (windowed !== null && (isLastRepresentableDate(windowed) || calendarFieldsOf(windowed.add({ days: 1 }), calendarId).month !== month.month)) return windowed; return floorDateForFields(calendarId, target); } function daysInMonth(calendarId, month) { const floor = lastDayFloor(calendarId, month); if (floor === null || isLastRepresentableDate(floor)) return null; const read = calendarFieldsOf(floor, calendarId); return read.year === month.year && read.month === month.month ? read.day : null; } /** The month code of `month`, or undefined when no day of it can be read. */ function monthCodeAt(calendarId, month) { const start = monthStart(calendarId, month); if (start !== void 0) return calendarFieldsOf(start, calendarId).monthCode; const floor = floorDateForFields(calendarId, { ...month, day: LAST }); const read = floor === null ? null : calendarFieldsOf(floor, calendarId); return read?.year === month.year && read.month === month.month ? read.monthCode : void 0; } /** * The ordinal of `monthCode` in `year`. By the month code grammar a code's ordinal is its number, * or one more when a leap month precedes it in that year, and a leap code `MxxL` directly follows * `Mxx` (the proposal allows at most one leap month per year). Both candidates are read back. */ function monthOrdinal(calendarId, year, monthCode) { const match = MONTH_CODE.exec(monthCode); if (!match) throw new RangeError(`Invalid month code: ${monthCode}`); const number = Number(match[1]); const candidates = match[2] === "L" ? [number + 1] : [number, number + 1]; let unreadable = false; for (const ordinal of candidates) { const code = monthCodeAt(calendarId, { year, month: ordinal }); if (code === monthCode) return ordinal; unreadable ||= code === void 0; } return unreadable ? null : "missing"; } /** The read-backed arithmetic model for a Temporal calendar id (one per calendar, memoized). */ function readArithmeticModel(calendarId) { let model = models.get(calendarId); if (model === void 0) { model = { calendarId, fields: (date) => calendarFieldsOf(date, calendarId), monthOrdinal: (year, monthCode) => monthOrdinal(calendarId, year, monthCode), addMonths: (start, months) => addMonths(calendarId, start, months), monthsBetween: (from, to) => monthsBetween(calendarId, from, to), daysInMonth: (month) => daysInMonth(calendarId, month), toDate: (year, month, day) => calendarDateFromFields(calendarId, { year, month, day }, "reject").withCalendar(ISO_CALENDAR) }; models.set(calendarId, model); } return model; } export { readArithmeticModel };