@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.
78 lines (76 loc) • 4.52 kB
JavaScript
import { Temporal } from "../../internal/temporal.js";
import { isValidDateTimeInterval } from "./validate/isValidDateTimeInterval.js";
import { divisionBoundary } from "../../internal/divisionBoundary.js";
import { exceedsPieceLimit, resolveMaxPieces } from "../../internal/maxPieces.js";
// src/plain/interval/intervalDivideEquallyDateTime.ts
const NANOSECONDS_PER_DAY = 86400000000000n;
/**
* Split a datetime interval into `n` equal-length sub-intervals.
*
* - Returns an array of `n` `{ start, end }` records that tile the original interval, each
* record's `end` equal to the next record's `start`.
* - Every piece is half-open `[start, end)`: a boundary belongs only to the piece that starts
* there, so the pieces share no value and together cover the interval exactly once (the rule
* CORE-6's `splitIntervalAt` uses).
* - Each boundary is `start + round((end - start) · i / n)` in integer nanoseconds, computed in
* `bigint`: the split is exact whenever the total divides evenly by `n`, and within half a
* nanosecond of the exact cut otherwise (an exact half rounds up), at any span length — the
* whole PlainDateTime range included.
* - 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.
* - Returns `[]` when `n` is not a positive integer, or on invalid input (unparseable
* start/end, `start > end`).
*
* @param start ISO PlainDateTime string for the interval start
* @param end ISO PlainDateTime string for the interval end
* @param n number of equal sub-intervals to produce (positive integer)
* @param options The limit on the size of the result
* @returns array of `n` `{ start, end }` records, or `[]` on invalid input
*
* @example intervalDivideEquallyDateTime("2024-01-01T00:00:00", "2024-01-04T00:00:00", 3) // [{ start: "2024-01-01T00:00:00", end: "2024-01-02T00:00:00" }, { start: "2024-01-02T00:00:00", end: "2024-01-03T00:00:00" }, { start: "2024-01-03T00:00:00", end: "2024-01-04T00:00:00" }]
* @example intervalDivideEquallyDateTime("2024-01-01T00:00:00", "2024-01-04T00:00:00", 1) // [{ start: "2024-01-01T00:00:00", end: "2024-01-04T00:00:00" }]
* @example intervalDivideEquallyDateTime("2024-01-01T00:00:00", "2024-01-04T00:00:00", 0) // []
* @example intervalDivideEquallyDateTime("invalid", "2024-01-04T00:00:00", 3) // []
* @example intervalDivideEquallyDateTime("2024-01-01T00:00:00", "2024-01-04T00:00:00", 3, { maxPieces: 2 }) // [] (3 pieces exceed the limit)
* @example intervalDivideEquallyDateTime("2024-01-01T00:00:00", "2024-01-04T00:00:00", 3, { maxPieces: 3 }) // [{ start: "2024-01-01T00:00:00", end: "2024-01-02T00:00:00" }, { start: "2024-01-02T00:00:00", end: "2024-01-03T00:00:00" }, { start: "2024-01-03T00:00:00", end: "2024-01-04T00:00:00" }]
*/
function intervalDivideEquallyDateTime(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 [];
if (!isValidDateTimeInterval(start, end)) return [];
try {
const startVal = Temporal.PlainDateTime.from(start);
const endVal = Temporal.PlainDateTime.from(end);
if (startVal.equals(endVal)) return Array.from({ length: n }, () => ({
start: startVal.toString(),
end: endVal.toString()
}));
const span = startVal.until(endVal, { largestUnit: "day" });
const totalNs = BigInt(span.days) * NANOSECONDS_PER_DAY + BigInt(span.hours) * 3600000000000n + BigInt(span.minutes) * 60000000000n + BigInt(span.seconds) * 1000000000n + BigInt(span.milliseconds) * 1000000n + BigInt(span.microseconds) * 1000n + BigInt(span.nanoseconds);
const boundaries = [startVal];
for (let i = 1; i < n; i++) {
const offsetNs = divisionBoundary(totalNs, i, n);
boundaries.push(startVal.add({
days: Number(offsetNs / NANOSECONDS_PER_DAY),
nanoseconds: Number(offsetNs % NANOSECONDS_PER_DAY)
}));
}
boundaries.push(endVal);
const result = [];
for (let i = 0; i < boundaries.length - 1; i++) result.push({
start: boundaries[i].toString(),
end: boundaries[i + 1].toString()
});
return result;
} catch {
return [];
}
} catch {
return [];
}
}
export { intervalDivideEquallyDateTime };