@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.
96 lines (94 loc) • 6.68 kB
JavaScript
import { Temporal } from "../../internal/temporal.js";
import { frameInstant } from "../../internal/zoneFrame.js";
import { resolveDurationUnit } from "../../internal/resolveDurationUnit.js";
import { toUnixEpoch } from "../../internal/unixEpochValue.js";
import { minSlicesForSpan, stepNoFinerThan, tileByUnit } from "../../internal/splitStep.js";
import { exceedsPieceLimit, resolveMaxPieces } from "../../internal/maxPieces.js";
import { resolveUnixIntervalPair } from "../../internal/resolveUnixIntervalPair.js";
// src/unix/interval/splitIntervalByUnitUnix.ts
/**
* Split a Unix epoch interval into sub-intervals of `amount × unit`.
*
* - Returns an array of half-open `[start, end)` records that tile the interval: each record's
* `end` is the next record's `start` and belongs only to that next record, so the pieces share
* no value and together cover `[start, end)` exactly once.
* - The final sub-interval is trimmed so its `end` never exceeds the original `end`.
* - Calendar-unit boundaries (years, months, weeks, days) are computed from `start`
* (`start + k × amount`), so month-end starts don't drift: a monthly split from January 31
* lands on February 29, March 31, April 30. Temporal's `add` constrains a day the month lacks
* to the month's last day, and stepping from that boundary would keep the shortened day
* (February 29, then March 29).
* - Each calendar-unit boundary is `start.add(amount × k)` with Temporal's
* `overflow: "constrain"` (TC39 Temporal `add`), never a step from the previous boundary.
* - Exact-unit boundaries (hours and smaller) step from the previous boundary. Exact units never
* clamp, and stepping keeps nanosecond precision where `k × amount` would pass
* `Number.MAX_SAFE_INTEGER` (boundaries are then floored to milliseconds).
* - A calendar step that resolves to the same instant as the previous boundary (a deleted local
* day, such as 30 December 2011 in `Pacific/Apia`) is skipped, so no empty slice is produced.
* A step that goes backwards returns `[]`.
* - A step finer than `epochUnit` (500 milliseconds when the epochs are seconds, any microsecond
* or nanosecond step shorter than a millisecond) cannot be written in that unit: its boundaries
* floor to every whole unit from `start` to `end`, so the pieces are one `epochUnit` long and
* none is empty. `maxPieces` counts those pieces.
* - Returns `[{ start, end }]` when `start === end` (zero-length interval).
* - Returns `[]` on invalid input (`start`/`end` that is not a safe integer or numeric string of
* one — fractions, empty strings and values beyond ±(2^53 − 1) are invalid — unsupported unit,
* non-positive amount, an invalid `epochUnit` or an unknown `timeZone`).
*
* - `start` and `end` are each a safe integer or a string of optionally negative ASCII digits.
* - Accepts singular or plural units (`"day"` and `"days"` behave identically).
* - A split into more than `options.maxPieces` slices returns `[]`, decided from the span before
* stepping where it can be, and otherwise as soon as slice `maxPieces + 1` is due.
* - **Limit at an offset with seconds.** The instant is placed in the offset's whole-minute zone,
* moved by its seconds, and the moved instant must be inside Temporal's range. So within the
* offset's seconds (under a minute) of the last instant Temporal supports
* (`+275760-09-13T00:00:00Z`) for an offset east of UTC, or of the first
* (`-271821-04-20T00:00:00Z`) for one west, this returns `[]`. An offset to the minute has no
* such limit.
*
* @param start Unix epoch in `epochUnit` — interval start
* @param end Unix epoch in `epochUnit` — interval end
* @param unit duration unit string — any `DateTimeDurationUnit`, singular or plural
* @param amount positive number of units per step
* @param options optional: the limit on the number of slices, how the epochs are read and the zone calendar steps run in
* @returns array of `{ start, end }` records, or [] on invalid input
*
* @example splitIntervalByUnitUnix(0, 86400000, "hour", 6) // [{ start: 0, end: 21600000 }, { start: 21600000, end: 43200000 }, { start: 43200000, end: 64800000 }, { start: 64800000, end: 86400000 }]
* @example splitIntervalByUnitUnix(0, 3600000, "hour", 1) // [{ start: 0, end: 3600000 }]
* @example splitIntervalByUnitUnix(0, 0, "hour", 1) // [{ start: 0, end: 0 }]
* @example splitIntervalByUnitUnix(0, 86400000, "hour", 0) // []
* @example splitIntervalByUnitUnix("invalid", 86400000, "hour", 1) // []
* @example splitIntervalByUnitUnix(0, 86400000, "hour", 6, { maxPieces: 3 }) // [] (4 slices exceed the limit)
* @example splitIntervalByUnitUnix(0, 86400000, "hour", 6, { maxPieces: 4 }) // [{ start: 0, end: 21600000 }, { start: 21600000, end: 43200000 }, { start: 43200000, end: 64800000 }, { start: 64800000, end: 86400000 }]
* @example splitIntervalByUnitUnix(1728136800000, 1728306000000, "day", 1, { timeZone: "Australia/Sydney" }) // [{ start: 1728136800000, end: 1728219600000 }, { start: 1728219600000, end: 1728306000000 }] (the first local day is 23 hours)
* @example splitIntervalByUnitUnix("0", "86400", "hours", 12, { epochUnit: "second" }) // [{ start: 0, end: 43200 }, { start: 43200, end: 86400 }]
* @example splitIntervalByUnitUnix(0, 2, "millisecond", 500, { epochUnit: "seconds" }) // [{ start: 0, end: 1 }, { start: 1, end: 2 }] (a step finer than the epoch unit gives one-second pieces)
*/
function splitIntervalByUnitUnix(start, end, unit, amount, options) {
try {
const pair = resolveUnixIntervalPair(start, end, unit, options);
if (pair === null) return [];
if (!Number.isFinite(amount) || amount <= 0) return [];
const maxPieces = resolveMaxPieces(options);
if (maxPieces === null) return [];
const { startVal, endVal, epochUnit, frame } = pair;
const [resolvedUnit, stepAmount] = stepNoFinerThan(resolveDurationUnit(pair.resolvedUnit), amount, epochUnit);
if (startVal.epochNanoseconds === endVal.epochNanoseconds) return [{
start: toUnixEpoch(frameInstant(startVal, frame), epochUnit),
end: toUnixEpoch(frameInstant(endVal, frame), epochUnit)
}];
try {
const spanNs = Number(endVal.epochNanoseconds - startVal.epochNanoseconds);
if (exceedsPieceLimit(minSlicesForSpan(spanNs, resolvedUnit, stepAmount, true), maxPieces)) return [];
return (tileByUnit(startVal, endVal, Temporal.ZonedDateTime.compare, resolvedUnit, stepAmount, maxPieces) ?? []).map(([sliceStart, sliceEnd]) => ({
start: toUnixEpoch(frameInstant(sliceStart, frame), epochUnit),
end: toUnixEpoch(frameInstant(sliceEnd, frame), epochUnit)
}));
} catch {
return [];
}
} catch {
return [];
}
}
export { splitIntervalByUnitUnix };