@nxtedition/ranges
v1.0.13
Published
Merge and subtract numeric ranges. Useful for byte ranges, time ranges, and similar interval arithmetic.
Downloads
2,686
Maintainers
Keywords
Readme
@nxtedition/ranges
Merge and subtract numeric ranges. Useful for byte ranges, time ranges, and similar interval arithmetic.
Requires Node.js 26 or newer.
Replaces @nxtedition/lib/merge-ranges (removed from @nxtedition/lib in v29.0.14).
Install
npm install @nxtedition/rangesUsage
Merge overlapping ranges
import { merge } from '@nxtedition/ranges'
merge([
[10, 20],
[15, 30],
[50, 60],
])
// [[10, 30], [50, 60]]Subtract ranges
import { subtract } from '@nxtedition/ranges'
subtract(
[[0, 100]],
[
[10, 20],
[30, 40],
],
)
// [[0, 10], [20, 30], [40, 100]]API
merge(ranges: readonly Range[]): readonly Range[]
Sorts and merges overlapping or adjacent ranges into a canonical list: sorted, disjoint, and fully coalesced. Invalid ranges (empty, reversed, non-finite, malformed) are filtered out. Does not modify the input, and the result never shares references with it.
subtract(a: readonly Range[], b: readonly Range[]): readonly Range[]
Subtracts the coverage of b from each range in a. Invalid ranges are filtered from both inputs — note this means an open-ended range like [x, Infinity] in b subtracts nothing.
Each a range is reduced independently and its remainders are emitted in a's order: the result is sorted and disjoint when a is (for example, the output of merge). If a contains overlapping, duplicate, or unsorted ranges, the result mirrors that shape — pass merge(a) first if you need canonical output.
b may be unsorted and overlapping. Does not modify the inputs, and the result never shares references with them.
Range
type Range = readonly [start: number, end: number]Ranges are half-open intervals: start is inclusive, end is exclusive. Negative-zero endpoints are normalized to 0 in the output.
Empty results
An empty result may be a shared, frozen empty array rather than a fresh one. The return type is readonly — copy before mutating.
License
MIT
