range-overlap
v1.0.0
Published
Are 2 ranges overlapping
Downloads
895
Maintainers
Readme
range-overlap
Are 2 ranges overlap ?, demo page.
Installation
Install with npm install range-overlap
then
// CommonJS
const { isRangeOverlap } = require('range-overlap')
// ES6
import { isRangeOverlap } from "range-overlap"
Example usage
// integer and floating numbers as a param
isRangeOverlap(1, 10, 2, 12) // true
isRangeOverlap(1, 10, 2, 8) // true
isRangeOverlap(100, 200, 201, 300) // false
// Date as a param
isRangeOverlap( // true
new Date(1615452500000),
new Date(1615452800000),
new Date(1615452700000),
new Date(1615452900000),
)
// array of numbers or Date(s) as a param
isRangeOverlap([1, 10], [2, 12]) // true
isRangeOverlap( // true
[new Date(1615452500000), new Date(1615452800000)],
[new Date(1615452700000), new Date(1615452900000)]
)
// custom type as a param
isRangeOverlap( // true
{ start: 1, end: 10 },
{ start: 2, end: 12 }
)
// support is-exclusive param
isRangeOverlap(1, 10, 10, 12, true) // false
isRangeOverlap( // false
new Date(1615452500000),
new Date(1615452600000),
new Date(1615452600000),
new Date(1615452800000),
true
)
isRangeOverlap([1, 10], [10, 12], true) // false
isRangeOverlap( // false
[new Date(1615452500000), new Date(1615452600000)],
[new Date(1615452600000), new Date(1615452800000)],
true
)
isRangeOverlap({ start: 1, end: 10 }, { start: 10, end: 12 }, true) // false
Algorithm
The detailed logic is described here, but in summary is explained below.
2 cases that will not overlapping
case1) |----range1----| |----range2----|
x1 x2 y1 y2
case2) |----range2----| |----range1----|
y1 y2 x1 x2
so isNotOverlap
= case1) or case2)
= x2 < y1 || y2 < x1
due to isOverlap
= ~isNotOverlap
= ~(x2 < y1 || y2 < x1)
= x2 >= y1 && y2 >= x1
= x1 <= y2 && y1 <= x2
CMD
npm run format && npm run lint && npm run coverage.check && npm run build
npx stryker run
npm run version
npm publish --dry-run
npm publish