AniUI Academy

Intersect two rectangles

mediumDOM & Utilities+250 XPPractice

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.

Arguments

a{ x: number; y: number; width: number; height: number }
The first rectangle in screen coordinates: x grows right and y grows down.
b{ x: number; y: number; width: number; height: number }
The second rectangle, in the same coordinate system.

Returns

{ x: number; y: number; width: number; height: number } | null — A new rectangle describing the overlap, or null when the rectangles do not overlap (edge-touching counts as not overlapping).

Examples

intersect(
  { x: 0, y: 0, width: 100, height: 100 },
  { x: 50, y: 50, width: 100, height: 100 }
);
// => { x: 50, y: 50, width: 50, height: 50 }

The lower-right quadrant of A overlaps the upper-left of B.

intersect(
  { x: 0, y: 0, width: 100, height: 100 },
  { x: 100, y: 0, width: 50, height: 100 }
);
// => null

Rectangles that only share an edge have zero-area overlap.

intersect(
  { x: 0, y: 0, width: 100, height: 100 },
  { x: 20, y: 30, width: 10, height: 10 }
);
// => { x: 20, y: 30, width: 10, height: 10 }

When one rectangle contains the other, the inner one is the overlap.

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.

Notes

  • This matches how IntersectionObserver and getBoundingClientRect think about rectangles — y grows downwards, so top < bottom numerically.
  • The null result for edge-touching rectangles is a judgement call; a hit-test for cursor-over-element usually wants the opposite. If you need inclusive touching, change the final guard to right < left || bottom < top.

Stuck? The javascript course covers everything this challenge needs.

Try it yourself
Loading playground...
5 tests · +250 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.