@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.
83 lines (81 loc) • 5.54 kB
JavaScript
import { Temporal } from "../../internal/temporal.js";
import { calendarOfAllZonedValues } from "../../internal/calendarValueOfZoned.js";
import { formatZonedInCalendar } from "../../internal/calendarZonedString.js";
import { calendarZonedIntervalOf } from "../../internal/intervalChecks.js";
import { divisionBoundary } from "../../internal/divisionBoundary.js";
import { exceedsPieceLimit, resolveMaxPieces } from "../../internal/maxPieces.js";
// src/zoned/interval/intervalDivideEquallyZoned.ts
/**
* Split a zoned interval into `n` equal-length sub-intervals.
*
* - Returns an array of `n` half-open `[start, end)` records that tile the original interval: each
* record's `end` is the next record's `start` and belongs only to that next record, so the
* pieces share no instant and together cover `[start, end)` exactly once.
* - Each boundary is `start + round((end - start) · i / n)` in integer epoch nanoseconds (real
* elapsed time, exact at any span length), so a spring-forward day split in half lands exactly
* on the DST transition's real midpoint rather than the local-clock midpoint.
* - When `n` is larger than the number of nanoseconds in the interval, some pieces are empty (their
* `start` equals their `end`): the result always has exactly `n` pieces.
* - `n === 1` returns the original interval unchanged, as a single-element array.
* - A zero-length interval (`start === end`) returns `n` identical zero-length sub-intervals, each
* an empty `[start, start)` that holds no instant.
* - `start` and `end` may name different time zones. The first `start` and every inner boundary
* are written in `start`'s zone; the last `end` is the `end` argument, in its own zone.
* - Returns `[]` when `n` is not a positive integer, or on invalid input (unparseable
* start/end, `start > end`, leap-second strings).
* - Accepts RFC 9557 calendar-annotated zoned strings (as produced by `convertZonedToCalendar`) as
* well as bare ISO ones — E7 (issue #152) — but **rejects a mismatched pair**: `start` and `end`
* must name the same calendar system (E7's D4-zoned), since the synthesized boundaries are
* values the caller reads back as datetimes and an array of differently-tagged records would be
* unreadable as a set. A mismatch returns `[]`.
* - Output boundaries are re-derived in the resolved calendar via `formatZonedInCalendar`, never
* copied from an input string (E7's D7-zoned).
* - An `n` over `options.maxPieces` returns `[]` before any piece is built.
*
* @param start ISO 8601 zoned datetime string for the interval start
* @param end ISO 8601 zoned datetime string for the interval end
* @param n number of equal sub-intervals to produce (positive integer)
* @param options optional limit on the size of the output
* @returns array of `n` `{ start, end }` records, or `[]` on invalid input
*
* @example intervalDivideEquallyZoned("2024-10-05T12:00:00+10:00[Australia/Sydney]", "2024-10-07T12:00:00+11:00[Australia/Sydney]", 2) // [{ start: "2024-10-05T12:00:00+10:00[Australia/Sydney]", end: "2024-10-06T12:30:00+11:00[Australia/Sydney]" }, { start: "2024-10-06T12:30:00+11:00[Australia/Sydney]", end: "2024-10-07T12:00:00+11:00[Australia/Sydney]" }] (47 real hours split in half)
* @example intervalDivideEquallyZoned("2024-01-01T00:00:00+00:00[UTC]", "2024-01-04T00:00:00+00:00[UTC]", 1) // [{ start: "2024-01-01T00:00:00+00:00[UTC]", end: "2024-01-04T00:00:00+00:00[UTC]" }]
* @example intervalDivideEquallyZoned("2024-01-01T00:00:00+00:00[UTC]", "2024-01-04T00:00:00+00:00[UTC]", 0) // []
* @example intervalDivideEquallyZoned("invalid", "2024-01-04T00:00:00+00:00[UTC]", 3) // []
* @example intervalDivideEquallyZoned("2024-01-01T00:00:00+00:00[UTC]", "2024-01-04T00:00:00+00:00[UTC]", 3, { maxPieces: 2 }) // [] (3 pieces exceed the limit)
* @example intervalDivideEquallyZoned("2024-01-01T00:00:00+00:00[UTC]", "2024-01-04T00:00:00+00:00[UTC]", 3, { maxPieces: 3 }) // [{ start: "2024-01-01T00:00:00+00:00[UTC]", end: "2024-01-02T00:00:00+00:00[UTC]" }, { start: "2024-01-02T00:00:00+00:00[UTC]", end: "2024-01-03T00:00:00+00:00[UTC]" }, { start: "2024-01-03T00:00:00+00:00[UTC]", end: "2024-01-04T00:00:00+00:00[UTC]" }]
*/
function intervalDivideEquallyZoned(start, end, n, options) {
try {
if (typeof n !== "number" || !Number.isInteger(n) || n <= 0) return [];
const maxPieces = resolveMaxPieces(options);
if (maxPieces === null || exceedsPieceLimit(n, maxPieces)) return [];
const interval = calendarZonedIntervalOf(start, end);
if (interval === null) return [];
const calendar = calendarOfAllZonedValues([start, end]);
if (!calendar) return [];
try {
const [startVal, endVal] = interval;
if (startVal.toInstant().equals(endVal.toInstant())) return Array.from({ length: n }, () => ({
start: formatZonedInCalendar(startVal, calendar),
end: formatZonedInCalendar(endVal, calendar)
}));
const startNs = startVal.epochNanoseconds;
const totalNs = endVal.epochNanoseconds - startNs;
const boundaries = [startVal];
for (let i = 1; i < n; i++) boundaries.push(new Temporal.ZonedDateTime(startNs + divisionBoundary(totalNs, i, n), startVal.timeZoneId, startVal.calendarId));
boundaries.push(endVal);
const result = [];
for (let i = 0; i < boundaries.length - 1; i++) result.push({
start: formatZonedInCalendar(boundaries[i], calendar),
end: formatZonedInCalendar(boundaries[i + 1], calendar)
});
return result;
} catch {
return [];
}
} catch {
return [];
}
}
export { intervalDivideEquallyZoned };