Created
December 21, 2014 15:49
-
-
Save adyatlov/fc3ebc7783bfafa13ae3 to your computer and use it in GitHub Desktop.
Simple library to check if intervals intersect. Support open, closed and partially closed intervals. Dedicated to Alex. Tests are here https://gist.github.com/benzel/ffb0851c6e22469cf662
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Boundary = function (value, type) { | |
this.value = value; | |
this.type = type; | |
} | |
Boundary.weightTable = { | |
")": 1, | |
"]": 2, | |
"[": 2, | |
"(": 3 | |
} | |
Boundary.prototype.lessThan = function (boundary) { | |
if (this.value < boundary.value) { | |
return 1; | |
} else if (this.value > boundary.value) { | |
return -1; | |
} else { // this.value === interval.value | |
var w1 = Boundary.weightTable[this.type]; | |
var w2 = Boundary.weightTable[boundary.type]; | |
if (w1 === w2) { | |
return 0; | |
} else if (w1 < w2) { | |
return 1; | |
} else { | |
return -1; | |
} | |
} | |
} | |
Interval = function (left, right) { | |
if (left.lessThan(right) < 0) { | |
throw left + " > " + right; | |
} | |
this.left = left; | |
this.right = right; | |
} | |
Interval.prototype.intersects = function (interval) { | |
// Sort | |
var first; | |
var second; | |
if (this.left.lessThan(interval.left) >= 0) { | |
first = this; | |
second = interval; | |
} else { | |
first = interval; | |
second = this; | |
} | |
if (first.right.lessThan(second.left) > 0) { | |
return false; | |
} else { | |
return true; | |
} | |
} | |
Interval.makeOpen = function (left, right) { | |
return new Interval(new Boundary(left, "("), | |
new Boundary(right, ")")); | |
} | |
Interval.makeClosed = function (left, right) { | |
return new Interval(new Boundary(left, "["), | |
new Boundary(right, "]")); | |
} | |
Interval.makeOpenLeft = function (left, right) { | |
return new Interval(new Boundary(left, "("), | |
new Boundary(right, "]")); | |
} | |
Interval.makeOpenRight = function (left, right) { | |
return new Interval(new Boundary(left, "["), | |
new Boundary(right, ")")); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment