AniUI Academy
medium+250 XPPractice

Intersect two rectangles

Every collision test, drop-target highlight and 'is this card in view' check reduces to intersecting two rectangles. Real code gets them from getBoundingClientRect(), but the geometry is pure arithmetic, so that is what you implement here.

A rectangle is a plain object { x, y, width, height }, where x grows to the right and y grows **downwards**, matching screen coordinates.

Implement intersect(a, b). Return a new rectangle { x, y, width, height } describing the overlap, or null when there is no overlap.

The overlap's left edge is the larger of the two left edges and its right edge is the smaller of the two right edges, and likewise vertically. Rectangles that merely touch along an edge produce a zero-width or zero-height region and count as **not** overlapping, so return null. Also return null if either input has a width or height that is zero or negative.

What it has to do

  • Return { x, y, width, height } for the overlapping region.
  • Return null when the rectangles do not overlap.
  • Treat edge-touching, zero-area overlap as no overlap.
  • Return null when either input rectangle has a zero or negative width or height.
  • Do not mutate either input rectangle.

Your workspace

Try it yourself
Loading playground...

Ready to check it?

5 tests run against your code, right here in your browser. Sign in to claim the XP when you pass.

AI Crack & Solution Assist

Stuck? Get instant AI hints or break down the optimal solution.

Stuck? The javascript course covers everything this challenge needs.