Skip to content

mergeIntervals

mergeIntervals<T>(intervals, compare, isAdjacent?): T[]

Defined in: interval/merge-intervals.ts:48

Sorts and coalesces intervals into the minimal set of disjoint, ascending, inclusive ranges covering exactly the points the input covered.

Intervals arrive and leave in the flat, stride-2 [start, end, start, end, …] form the rest of interval/ uses, so the result can be handed straight to isInSortedIntervals.

Two intervals coalesce when they overlap or touch at a point: [1, 5] and [5, 9] become [1, 9], because 5 is in both. Touching and adjacent are not the same question, and only the first is answered by default. [1, 2] and [3, 4] share no point, so whether they should still become [1, 4] turns on whether anything lies strictly between 2 and 3 — over the integers nothing does, over the reals 2.5 does, and over a Date it depends on whether the caller is counting milliseconds or instants. The bound type alone cannot settle it, so isAdjacent is how the caller says what the successor of a bound is. Omit it and only overlaps merge.

An interval whose start compares after its end covers no point and is dropped: the result is the union of the inputs, and an empty interval contributes nothing to a union.

Complexity: O(n log n) in the interval count, dominated by the sort; O(n) extra space. isAdjacent, when given, is called at most once per interval, on already-sorted neighbours that do not overlap.

T

readonly T[]

Flat [start, end, …] pairs, in any order, possibly overlapping.

Comparator<T>

Total order over the bound type.

IntervalAdjacency<T>

Successor test for a discrete bound type; omit for a dense one.

T[]

A fresh flat array, ascending by start, holding no two intervals that overlap, touch, or satisfy isAdjacent.

When intervals holds an odd number of bounds.