JavaScript经典面试题:判断两个矩形是否重叠

题目:用一个对象的数据来表示一个矩形的位置和大小:

{
  x: 100,
  y: 100,
  width: 150,
  height: 250
}

它表示一个宽为 150 高为 250 的矩形在页面上的 (100, 100) 的位置。

请你完成一个函数 isOverlap 可以接受两个矩形作为参数,判断这两个矩形在页面上是否重叠。例如:

const rect1 = { x: 100, y: 100, width: 100, height: 100 }
const rect2 = { x: 150, y: 150, width: 100, height: 100 }
isOverlap(rect1, rect2) // => true

答案:

// 原理:http://www.geeksforgeeks.org/find-two-rectangles-overlap/
const isOverlap = (rect1, rect2) => {
  const l1 = { x: rect1.x, y: rect1.y }
  const r1 = { x: rect1.x + rect1.width, y: rect1.y + rect1.height }
  const l2 = { x: rect2.x, y: rect2.y }
  const r2 = { x: rect2.x + rect2.width, y: rect2.y + rect2.height }
  if (
    l1.x > r2.x ||
    l2.x > r1.x ||
    l1.y > r2.y ||
    l2.y > r1.y
  ) return false
  return true
}
THE END