This is my solution to find the coordinates of 2 overlapped rectangles implemented in JavaScript. Each rectangle is represented by 2 points, each with 2 (x,y) coordinates.
Can this code be improved?
const maxOfX = (rec) => (Math.max(rec.x1, rec.x2));
const maxOfY = (rec) => (Math.max(rec.y1, rec.y2));
const minOfX = (rec) => (Math.min(rec.x1, rec.x2));
const minOfY = (rec) => (Math.min(rec.y1, rec.y2));
const comBinedRectangle = (rec1, rec2) => {
let overlappedRec = {};
const NolappingFromX = maxOfX(rec1) <= minOfX(rec2) || minOfX(rec1) >= maxOfX(rec2);
const NolappingFromY = maxOfY(rec1) <= minOfY(rec2) || minOfY(rec1) >= maxOfY(rec2);
if (!(NolappingFromX || NolappingFromY)) {
overlappedRec.x1 = Math.max(minOfX(rec1), minOfX(rec2));
overlappedRec.y1 = Math.max(minOfY(rec1), minOfY(rec2));
overlappedRec.x2 = Math.min(maxOfX(rec1), maxOfX(rec2));
overlappedRec.y2 = Math.min(maxOfY(rec1), maxOfY(rec2));
}
return overlappedRec;
}
const rectangle1 = { x1: 2, y1: 2, x2: 4, y2: 4 };
const rectangle2 = { x1: 3, y1: 3, x2: 6, y2: 2 };
console.log(comBinedRectangle(rectangle1, rectangle2));
// { x1: 3, y1: 2, x2: 4, y2: 3 }
(boolean expression) ? true : false
. Try to limit line length. \$\endgroup\$rect1.intersects(rect2)
\$\endgroup\$