All files perimeter.ts

100% Statements 10/10
100% Branches 2/2
100% Functions 1/1
100% Lines 10/10

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34  1x 1x                                       1x 8x   8x 25x   25x 25x   8x 8x  
import { type Polygon } from './@types/geometry.ts';
import { lineLength } from './line-length.ts';
import { modulo } from './modulo.ts';
 
/**
 * Calculates the perimeter of a polygon.
 * @param polygon - The polygon.
 * @returns The total perimeter length of the polygon.
 * @example
 * ```typescript
 * const polygon: Polygon = [
 *   { x: 0, y: 0 },
 *   { x: 10, y: 0 },
 *   { x: 10, y: 10 },
 *   { x: 0, y: 10 }
 * ];
 * const result = perimeter(polygon);
 * // result: 40
 * ```
 * @group Geometry
 * @category Polygon
 */
export function perimeter(polygon: Polygon): number {
  let total = 0;
 
  for (const [index, vertex0] of polygon.entries()) {
    const vertex1 = polygon[modulo(index + 1, polygon.length)];
 
    total += lineLength({ x0: vertex0.x, y0: vertex0.y, x1: vertex1.x, y1: vertex1.y });
  }
 
  return total;
}