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.

163 lines (161 loc) • 8.96 kB
import { isDefectPresent } from "./capabilities.js"; import { hebrewArithmeticModel } from "./hebrewArithmetic.js"; import { indianArithmeticModel } from "./indianArithmetic.js"; import { calendarFieldsOf, hasReadCorrection, polyfillCannotReturn, polyfillMisreadsIslamicEra } from "./calendarFields.js"; import { fixedMonthsPerYearOf, isLargeMonthSpan, isLargeYearSpan } from "./largeMonthSpan.js"; import { isNonIsoDateUntilResult, nonIsoDateAdd, nonIsoDateUntil } from "./nonIsoArithmetic.js"; import { readArithmeticModel } from "./readArithmeticModel.js"; // src/internal/temporalCompat/calendarDateArithmetic.ts const ISO_CALENDAR = "iso8601"; const DATE_UNITS = /* @__PURE__ */ new Set([ "year", "month", "week", "day" ]); /** * The owned Hebrew and Indian arithmetic answers whenever an operation's years come within this * many years of the corrected range, so that no step of it (a Surpasses candidate overshoots by at * most one unit) reaches the runtime's wrong reads or arithmetic. */ const CORRECTED_RANGE_MARGIN_YEARS = 2; const ownedModels = { hebrew: hebrewArithmeticModel, indian: indianArithmeticModel }; function fieldsOf(duration) { return { years: duration.years, months: duration.months, weeks: duration.weeks, days: duration.days }; } /** * D2: while buddhist reads are corrected, buddhist arithmetic is ISO arithmetic. The Intl * era/monthCode proposal makes buddhist month numbers, month codes and days identical to ISO 8601 * with year = ISO year + 543, so NonISODateAdd/Until give exactly the ISO results. */ function usesIsoArithmetic(calendarId) { return calendarId === "buddhist" && hasReadCorrection(calendarId, Number.NEGATIVE_INFINITY); } /** The owned model for `calendarId` when its read correction is active in this runtime. */ function activeOwnedModel(calendarId) { const model = ownedModels[calendarId]; return model !== void 0 && hasReadCorrection(calendarId, Number.NEGATIVE_INFINITY) ? model : void 0; } /** The arithmetic model `calendarId` is computed with: the owned one where active, else the read-backed one. */ function arithmeticModelFor(calendarId) { return activeOwnedModel(calendarId) ?? readArithmeticModel(calendarId); } function reachesCorrectedRange(calendarId, years) { return hasReadCorrection(calendarId, Math.min(...years) - CORRECTED_RANGE_MARGIN_YEARS); } /** * D18: true when an operation over `years` may ask the polyfill about a year it cannot return * from, with the same margin as the owned models. Such an operation runs the spec loops over the * read-backed model, whose every step avoids the polyfill for those years. */ function reachesPolyfillLimit(calendarId, years) { return polyfillCannotReturn(calendarId, Math.min(...years) - CORRECTED_RANGE_MARGIN_YEARS); } /** * The lowest calendar year `date + fields` can land in, for `reachesPolyfillLimit`: whole years * plus the months as years, at the month count of a calendar the polyfill cannot answer for. */ function lowestYearOfSum(calendarId, startYear, fields) { const perYear = fixedMonthsPerYearOf(calendarId) ?? 1; return Math.min(startYear, startYear + fields.years + Math.floor(Math.min(fields.months, 0) / perYear)); } function untilWorkaroundNeeded(calendarId) { return isDefectPresent("D1", calendarId) || isDefectPresent("D10", calendarId) || isDefectPresent("D6", calendarId) || isDefectPresent("D7", calendarId); } function verifiedPolyfillUntil(one, two, largestUnit) { const calendarId = one.calendarId; if (largestUnit === "month" && isLargeYearSpan(calendarFieldsOf(one, calendarId).year, calendarFieldsOf(two, calendarId).year)) return nonIsoDateUntil(readArithmeticModel(calendarId), one, two, largestUnit); let result; try { result = fieldsOf(one.until(two, { largestUnit })); } catch (error) { if (error instanceof RangeError && !untilWorkaroundNeeded(calendarId)) throw error; return nonIsoDateUntil(readArithmeticModel(calendarId), one, two, largestUnit); } if (!isDefectPresent("D6", calendarId) && !isDefectPresent("D7", calendarId)) return result; const model = readArithmeticModel(calendarId); return isNonIsoDateUntilResult(model, one, two, largestUnit, result) ? result : nonIsoDateUntil(model, one, two, largestUnit); } /** * `one.until(two, { largestUnit })`'s date fields, made correct where `@js-temporal/polyfill` is not * (TC39 `CalendarDateUntil`, Intl era/monthCode proposal `NonISODateUntil`). Both dates must carry * the same calendar. * * - `iso8601` is the polyfill's own `until`, untouched. * - `"day"` / `"week"` are ISO `until`: days do not depend on the calendar. * - D6/D7: the polyfill answers first; while its probe fails, the answer is kept only when it is * exactly the spec's (`isNonIsoDateUntilResult`), otherwise the spec loops recompute it. * - D1: a polyfill RangeError near a range limit is answered by the spec loops. * - D2/D3/D4/D5: in a corrected range the spec loops run over ISO (buddhist) or the owned Hebrew * and Indian arithmetic. * - D9: months counted across `LARGE_MONTH_SPAN` months or more run the spec loops, whose month * counts are bounded. * - D18: an Islamic year the polyfill cannot return from (<= 1 in WebKit) at either end runs the * spec loops over the read-backed model, without asking the polyfill. */ function calendarDateUntil(one, two, largestUnit) { const calendarId = one.calendarId; if (calendarId === ISO_CALENDAR) return fieldsOf(one.until(two, { largestUnit })); if (!DATE_UNITS.has(largestUnit)) throw new RangeError(`${String(largestUnit)} is not a date unit`); if (largestUnit === "week" || largestUnit === "day" || usesIsoArithmetic(calendarId)) return fieldsOf(one.withCalendar(ISO_CALENDAR).until(two.withCalendar(ISO_CALENDAR), { largestUnit })); const owned = activeOwnedModel(calendarId); if (owned !== void 0 && reachesCorrectedRange(calendarId, [owned.fields(one).year, owned.fields(two).year])) return nonIsoDateUntil(owned, one, two, largestUnit); if (reachesPolyfillLimit(calendarId, [calendarFieldsOf(one, calendarId).year, calendarFieldsOf(two, calendarId).year])) return nonIsoDateUntil(readArithmeticModel(calendarId), one, two, largestUnit); return verifiedPolyfillUntil(one, two, largestUnit); } /** * The owned (Hebrew, Indian) model's sum, when `date`'s calendar has an active owned model and * either end reaches the corrected range; otherwise undefined, and the polyfill answers. */ function ownedDateAdd(date, fields, overflow) { const calendarId = date.calendarId; const owned = activeOwnedModel(calendarId); if (owned === void 0) return; const result = nonIsoDateAdd(owned, date, fields, overflow); return reachesCorrectedRange(calendarId, [owned.fields(date).year, owned.fields(result).year]) ? result.withCalendar(calendarId) : void 0; } /** * `date.add(duration, { overflow })`, made correct where `@js-temporal/polyfill` is not (TC39 * `CalendarDateAdd`, Intl era/monthCode proposal `NonISODateAdd`). * * - `iso8601` is the polyfill's own `add`, untouched. * - Weeks and days alone are ISO day arithmetic. * - D1: a polyfill RangeError near a range limit is answered by the spec algorithm. * - D2/D3/D4/D5: in a corrected range the spec algorithm runs over ISO (buddhist) or the owned * Hebrew and Indian arithmetic. * - D9: `LARGE_MONTH_SPAN` months or more run the spec algorithm, whose month jumps are bounded. * - D18: a sum that may reach an Islamic year the polyfill cannot return from (<= 1 in WebKit) * runs the spec algorithm over the read-backed model, without asking the polyfill. * * @returns a PlainDate in `date`'s calendar; throws RangeError out of range or on `reject` */ function calendarDateAdd(date, duration, overflow) { const calendarId = date.calendarId; if (calendarId === ISO_CALENDAR) return date.add(duration, { overflow }); const fields = { years: duration.years ?? 0, months: duration.months ?? 0, weeks: duration.weeks ?? 0, days: duration.days ?? 0 }; if (fields.years === 0 && fields.months === 0 || usesIsoArithmetic(calendarId)) return date.withCalendar(ISO_CALENDAR).add(fields, { overflow }).withCalendar(calendarId); const ownedResult = ownedDateAdd(date, fields, overflow); if (ownedResult !== void 0) return ownedResult; if (polyfillMisreadsIslamicEra(calendarId) && reachesPolyfillLimit(calendarId, [lowestYearOfSum(calendarId, calendarFieldsOf(date, calendarId).year, fields)])) return nonIsoDateAdd(readArithmeticModel(calendarId), date, fields, overflow).withCalendar(calendarId); if (isLargeMonthSpan(fields.months)) return nonIsoDateAdd(readArithmeticModel(calendarId), date, fields, overflow).withCalendar(calendarId); try { return date.add(fields, { overflow }); } catch (error) { if (error instanceof RangeError && !isDefectPresent("D1", calendarId) && !isDefectPresent("D10", calendarId)) throw error; return nonIsoDateAdd(readArithmeticModel(calendarId), date, fields, overflow).withCalendar(calendarId); } } export { arithmeticModelFor, calendarDateAdd, calendarDateUntil };