Find the intersection of N intervals using a variant of Marzullo's algorithm.
yarn add intersecting-ranges
intersectingRanges(ranges [, options]);
option | type | default | description |
---|---|---|---|
omitEmpty |
boolean | true | Don't return the original ranges if there are no overlaps |
withData |
boolean | false | Optionally store data for each range to be merged into the intersections |
Example using ranges in the picture
const intersectingRanges = require("intersecting-ranges");
const ranges = [
[1, 31], // pink
[3, 10, { foo: 1 }], // orange
[13, 20], // orange
[23, 29], // orange
[4, 15], // green
[16, 30], // green
[1, 7, { bar: 2 }], // blue
[9, 24] // blue
];
intersectingRanges(ranges);
/* =>
[ [ 4, 7 ],
[ 9, 10 ],
[ 13, 15 ],
[ 16, 20 ],
[ 23, 24 ] ]
*/
intersectingRanges(ranges, { withData: true });
/* =>
[ [ 4, 7, { foo: 1, bar: 2 } ],
[ 9, 10, { foo: 1 } ],
[ 13, 15 ],
[ 16, 20 ],
[ 23, 24 ] ]
*/
With/without omitEmpty
option
const ranges = [[1, 31], [34, 36]];
intersectingRanges(ranges);
// []
intersectingRanges(ranges, { omitEmpty: false });
// [[1, 31], [34, 36]];