Check if a rectangle contains another one
Compare corners: a contains b when b’s corners sit inside or on a’s edges.
function contains({ a, b }) { return a.x1 <= b.x1 && a.y1 <= b.y1 && a.x2 >= b.x2 && a.y2 >= b.y2; }
Input & expected output
Input
{
"a": {
"x1": 0,
"y1": 0,
"x2": 10,
"y2": 10
},
"b": {
"x1": 2,
"y1": 2,
"x2": 5,
"y2": 5
}
}Expected output
trueThe edge case
Input
{
"a": {
"x1": 0,
"y1": 0,
"x2": 4,
"y2": 4
},
"b": {
"x1": 2,
"y1": 2,
"x2": 5,
"y2": 5
}
}Expected output
falseKnow the limits
- (x1, y1) is the top-left and (x2, y2) the bottom-right corner; the lab requires x1 ≤ x2 and y1 ≤ y2.
- Shared edges count as contained.
The function above is the implementation used by the lab. The lab validates JSON types and caps size before execution; include equivalent validation when accepting untrusted input in your application.
Source & maintenance
Based on Check if a rectangle contains other one from the original 1loc collection by Nguyen Huu Phuoc. Copyright (c) 2020 phuoc-ng. MIT licensed.
Original comparison kept; single-object input, corner-order validation and edge semantics. Original MDX retained as inert source evidence.
Maintained by Oveyon. Source commit: 14b481cf60df. Read the license.
Keep exploring
- Convert degrees to radians — Multiply by π and divide by 180.
- Check if a rectangle overlaps another one — Two rectangles overlap when they overlap on both axes.
- Calculate the angle of a line defined by two points — Use Math.atan2 for the angle from the x axis, in radians or degrees.