@technobuddha/library
Version:
A large library of useful functions
48 lines (43 loc) • 1.17 kB
text/typescript
import { type Polygon, type Rect } from './@types/geometry.ts';
/**
* Calculates the axis-aligned bounding rectangle for a given polygon.
* @param vertices - The polygon.
* @returns A {@link Rect} representing the smallest rectangle that contains the polygon.
* @throws `TypeError` If the polygon has fewer than three vertices.
* @example
* ```typescript
* bounds([
* { x: 0, y: 0 },
* { x: 0, y: 5 },
* { x: 10, y: 5 },
* { x: 10, y: 0 },
* ]);
* // { x: 0, y: 0, width: 10, height: 5 }
* ```
* @group Geometry
* @category Polygon
*/
export function bounds(vertices: Polygon): Rect {
if (vertices.length < 3) {
throw new TypeError('Cannot calculate bounds for an polygon with less than three sides.');
}
let xMin = Infinity;
let xMax = -Infinity;
let yMin = Infinity;
let yMax = -Infinity;
for (const vertex of vertices) {
if (vertex.x < xMin) {
xMin = vertex.x;
}
if (vertex.x > xMax) {
xMax = vertex.x;
}
if (vertex.y < yMin) {
yMin = vertex.y;
}
if (vertex.y > yMax) {
yMax = vertex.y;
}
}
return { x: xMin, y: yMin, width: xMax - xMin, height: yMax - yMin };
}