Look at the question from another site.
The case turns out to be quite simple if we look at the problem (algorithm) from the other side .
This means that instead of answering the question: βAre the rectangles overlapping?β, We will answer the question: βAre the rectangles overlapping?β.
In the end, both questions solve the same problem, but the answer to the second question is easier to implement because the rectangles do not overlap only when one is under the other or when one is to the left of the other (this is enough for one of these cases , but, of course, it can happen that both happen simultaneously - here a good understanding of the logical condition is βorβ important). This reduces many cases that need to be addressed on the first issue.
The whole question is also simplified by using the appropriate variable names :
const areRectanglesOverlap = (rect1, rect2) => { let [left1, top1, right1, bottom1] = [rect1[0], rect1[1], rect1[2], rect1[3]], [left2, top2, right2, bottom2] = [rect2[0], rect2[1], rect2[2], rect2[3]]; // The first rectangle is under the second or vice versa if (top1 < bottom2 || top2 < bottom1) { return false; } // The first rectangle is to the left of the second or vice versa if (right1 < left2 || right2 < left1) { return false; } // Rectangles overlap return true; }
Even if we have a different representation of the rectangle, it is easy to adapt the above function to it, changing only the section in which the changes to the variables are defined. A further part of the function remains unchanged (of course, comments are not really needed here, but I added them so that everyone can quickly understand this simple algorithm).
An equivalent but perhaps slightly less readable form of the above function might look like this:
const areRectanglesOverlap = (rect1, rect2) => { let [left1, top1, right1, bottom1] = [...rect1], [left2, top2, right2, bottom2] = [...rect2]; return !(top1 < bottom2 || top2 < bottom1 || right1 < left2 || right2 < left1); }