Checking For Range Overlap
I am trying to implement a function which, when given two objects that represent lines, returns whether they overlap or not. Here is how it should look like visually. Example 1: ch
Solution 1:
Nina Scholz answer won't work, eg. a = {start: 1, end: 2}, b = {start: 0, end: 10}.
If lines {start: 0, end: 10} and {start: 10, end: 15} are count as overlapping:
functioncheckOverlap(lineA, lineB) {
return lineA.start >= lineB.start && lineA.start <= lineB.end ||
lineA.end >= lineB.start && lineA.end <= lineB.end ||
lineB.start >= lineA.start && lineB.start <= lineA.end ||
lineB.end >= lineA.start && lineB.end <= lineA.end;
}
If not:
functioncheckOverlap(lineA, lineB) {
return lineA.start > lineB.start && lineA.start < lineB.end ||
lineA.end > lineB.start && lineA.end < lineB.end ||
lineB.start > lineA.start && lineB.start < lineA.end ||
lineB.end > lineA.start && lineB.end < lineA.end;
}
Solution 2:
You could check against the borders of an object.
functioncheckOverlap(o1, o2) {
return (
o1.start >= o2.start && o1.start <= o2.end ||
o1.end >= o2.start && o1.end <= o2.end ||
o2.start >= o1.start && o2.start <= o1.end ||
o2.end >= o1.start && o2.end <= o1.end
);
}
console.log(checkOverlap({start: 0, end: 10}, {start: 8, end: 15})); // trueconsole.log(checkOverlap({start: 8, end: 15}, {start: 0, end: 10})); // trueconsole.log(checkOverlap({start: 12, end: 15}, {start: 0, end: 10})); // falseconsole.log(checkOverlap({start: 0, end: 10}, {start: 12, end: 15})); // falseconsole.log(checkOverlap({start: 12, end: 15}, {start: 16, end: 17})); // falseconsole.log(checkOverlap({start: 16, end: 17}, {start: 12, end: 15})); // falseconsole.log(checkOverlap({start: 1, end: 2}, {start: 0, end: 10})); // trueconsole.log(checkOverlap({start: 0, end: 10}, {start: 1, end: 2})); // trueconsole.log(checkOverlap({start: 0, end: 10}, {start: 10, end: 20})); // trueconsole.log(checkOverlap({start: 10, end: 20}, {start: 0, end: 10})); // true
.as-console-wrapper { max-height: 100%!important; top: 0; }
Post a Comment for "Checking For Range Overlap"