@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.
164 lines (162 loc) • 6.72 kB
JavaScript
import { Temporal } from "../temporal.js";
import { calendarFieldsOf } from "./calendarFields.js";
import { calendarDateFromFields } from "./calendarDateFromFields.js";
// src/internal/temporalCompat/largeMonthSpan.ts
/** Month amounts from here on take the year jumps; below it the polyfill costs about 10 ms. */
const LARGE_MONTH_SPAN = 1200;
/** Intl era/monthCode proposal §4.1.4 Table 3: the calendars with leap month codes (`MxxL`). */
const LEAP_MONTH_CALENDARS = /* @__PURE__ */ new Set([
"chinese",
"dangi",
"hebrew"
]);
const ISO_CALENDAR = "iso8601";
/** Years whose month counts are read one by one before any mean is trusted. */
const SUMMED_YEARS = 64;
/** Year jumps stop this many years short of the estimate, so the remainder keeps its sign. */
const MARGIN_YEARS = 2;
/** The largest distance, in mean months, a span may be from a whole month count. */
const RESIDUAL_LIMIT = 1 / 3;
const profiles = /* @__PURE__ */ new Map();
function yearStart(calendarId, year) {
try {
return calendarDateFromFields(calendarId, {
year,
month: 1,
day: 1
}, "reject");
} catch (error) {
if (error instanceof RangeError) return;
throw error;
}
}
function daysBetween(one, two) {
return one.withCalendar(ISO_CALENDAR).until(two.withCalendar(ISO_CALENDAR), { largestUnit: "days" }).days;
}
/** The ordinal of `year`'s last month, read from the day before the next year starts. */
function monthsInYear(calendarId, year) {
const next = yearStart(calendarId, year + 1);
const read = next === void 0 ? void 0 : calendarFieldsOf(next.subtract({ days: 1 }), calendarId);
if (read?.year !== year) throw new RangeError(`${calendarId} year ${year} is not fully in range`);
return read.month;
}
/** Months in whole years `[from, from + years)`, read one year at a time. */
function summedMonths(calendarId, from, years) {
let months = 0;
for (let year = from; year < from + years; year++) months += monthsInYear(calendarId, year);
return months;
}
/** `days / meanMonthDays` when it is within `RESIDUAL_LIMIT` of a whole number of months. */
function wholeMonths(days, meanMonthDays) {
const months = Math.round(days / meanMonthDays);
if (Math.abs(days - months * meanMonthDays) > RESIDUAL_LIMIT * meanMonthDays) throw new RangeError("Month count is not determined by the day span");
return months;
}
function measureProfile(calendarId) {
const base = calendarFieldsOf(Temporal.PlainDate.from("2000-01-01"), calendarId).year;
if (!LEAP_MONTH_CALENDARS.has(calendarId)) {
const months = monthsInYear(calendarId, base);
return {
fixedMonthsPerYear: months,
meanMonthsPerYear: months
};
}
const start = yearStart(calendarId, base);
const summedEnd = yearStart(calendarId, base + SUMMED_YEARS);
if (start === void 0 || summedEnd === void 0) throw new RangeError(`${calendarId} has no modern years to measure`);
let months = summedMonths(calendarId, base, SUMMED_YEARS);
let meanMonthDays = daysBetween(start, summedEnd) / months;
let years = SUMMED_YEARS;
for (;;) {
const end = yearStart(calendarId, base + 2 * years);
if (end === void 0) break;
years *= 2;
const days = daysBetween(start, end);
months = wholeMonths(days, meanMonthDays);
meanMonthDays = days / months;
}
return {
meanMonthDays,
meanMonthsPerYear: months / years
};
}
function profileOf(calendarId) {
let profile = profiles.get(calendarId);
if (profile === void 0) {
profile = measureProfile(calendarId);
profiles.set(calendarId, profile);
}
return profile;
}
/**
* Months from the start of `fromYear` to the start of `toYear` (negative when `toYear` is
* earlier); `null` when a leap-month calendar cannot place one of those year starts, which lies
* outside the range.
*/
function monthsBetweenYearStarts(calendarId, fromYear, toYear) {
const profile = profileOf(calendarId);
if (profile.fixedMonthsPerYear !== void 0) return (toYear - fromYear) * profile.fixedMonthsPerYear;
const sign = Math.sign(toYear - fromYear);
const low = Math.min(fromYear, toYear);
const years = Math.abs(toYear - fromYear);
if (years <= SUMMED_YEARS) return sign * summedMonths(calendarId, low, years);
const start = yearStart(calendarId, fromYear);
const end = yearStart(calendarId, toYear);
if (start === void 0 || end === void 0) return null;
if (profile.meanMonthDays === void 0) throw new RangeError(`${calendarId} has no measured mean month length`);
return wholeMonths(daysBetween(start, end), profile.meanMonthDays);
}
/**
* Months in every year of `calendarId`, read from the runtime, or undefined for a calendar with
* leap months. Measuring it asks the polyfill about a modern year only.
*/
function fixedMonthsPerYearOf(calendarId) {
return profileOf(calendarId).fixedMonthsPerYear;
}
/** True when an amount of months is large enough for the year jumps. */
function isLargeMonthSpan(months) {
return Math.abs(months) >= LARGE_MONTH_SPAN;
}
/** True when two calendar years are far enough apart for the year jumps. */
function isLargeYearSpan(fromYear, toYear) {
return Math.abs(toYear - fromYear) * 12 >= LARGE_MONTH_SPAN;
}
/**
* `BalanceNonISODate(start.year, start.month + months, 1)` for a large `months`: step to the next
* (or previous) year start, jump whole years, and let `addSmall` finish the few years left.
* `null` when the result lies outside the range.
*/
function addManyMonths(calendarId, start, months, addSmall, betweenSmall) {
const sign = Math.sign(months);
const first = {
year: start.year + sign,
month: 1
};
if (yearStart(calendarId, first.year) === void 0) return null;
const remaining = months - betweenSmall(start, first);
const years = sign * Math.max(0, Math.floor(Math.abs(remaining) / profileOf(calendarId).meanMonthsPerYear) - MARGIN_YEARS);
const consumed = monthsBetweenYearStarts(calendarId, first.year, first.year + years);
return consumed === null ? null : addSmall({
year: first.year + years,
month: 1
}, remaining - consumed);
}
/**
* The signed month count from `from` to `to` (both month starts in range) when they are years
* apart: the months to the first whole year, the whole years, and the months after the last.
*/
function countManyMonths(calendarId, from, to, betweenSmall) {
const forward = to.year > from.year;
const first = {
year: from.year + (forward ? 1 : 0),
month: 1
};
const last = {
year: to.year + (forward ? 0 : 1),
month: 1
};
const whole = monthsBetweenYearStarts(calendarId, first.year, last.year);
if (whole === null) throw new RangeError(`Cannot count ${calendarId} months from ${from.year} to ${to.year}`);
return betweenSmall(from, first) + whole + betweenSmall(last, to);
}
export { addManyMonths, countManyMonths, fixedMonthsPerYearOf, isLargeMonthSpan, isLargeYearSpan };