JSFiddle - React, Tailwind, and code Playground

Rectangular intersection

by Varayut Lerdkanlayanawat

JavaScript

// https://www.interviewcake.com/question/javascript/rectangular-love#range-overlap-cases

function findRangeOverlap(point1, width1, point2, width2) {
	const highestStartPoint = Math.max(point1, point2);
  const lowestEndPoint = Math.min(point1 + width1, point2 + width2);
  
  if (highestStartPoint > lowestEndPoint) {
  	return { startPoint: null, width: null };
  }
  
  const overlapWidth = lowestEndPoint - highestStartPoint;
  
  return { startPoint: highestStartPoint, width: overlapWidth };
}

function findRectangularOverlap(rect1, rect2) {
	const xOverlap = findRangeOverlap(rect1.leftX, rect1.width, rect2.leftX, rect2.width);
	const yOverlap = findRangeOverlap(rect1.bottomY, rect1.height, rect2.bottomY, rect2.height);
  
  if (!xOverlap.width || !yOverlap.width) {
  	return {
      leftX: null,
      bottomY: null,
      width: null,
      height: null
    }
  }
  
 return {
    leftX: xOverlap.startPoint,
    bottomY: yOverlap.startPoint,
    width: xOverlap.width,
    height: yOverlap.width,
  }; 
}

const rec1 = {
  // coordinates of bottom-left corner
  leftX: 1,
  bottomY: 5,

  // width and height
  width: 10,
  height: 5,
};

const rec2 = {
  // coordinates of bottom-left corner
  leftX: 9,
  bottomY: 7,

  // width and height
  width: 5,
  height: 3,
};
console.log(findRectangularOverlap(rec1, rec2));