sal sal - 20 days ago 5
Javascript Question

javascript: checking for number 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:

checkOverlap({start: 0, end: 10}, {start: 8, end: 15})

Which visually, would be:

0--------10

8-------15
^ over lap


Returns:

true

Example 2:

checkOverlap({start: 12, end: 15}, {start: 0, end: 10})

Which visually, would be:

12-------15


0--------10

no overlap


Returns:

false

here is my function which works for some but not all,

function checkOverlap(lineA, lineB) {


var result;

for(var a in lineA){
for(var b in lineB){
if(a.end > b.start){
result = true;
} else {
result = true;
}
}
} return result;}

Answer

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:

 function checkOverlap(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:

 function checkOverlap(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;
    }
Comments