All files / packages/tools/src/utilities/math/polyline getArea.ts

100% Statements 8/8
100% Branches 0/0
100% Functions 1/1
100% Lines 7/7

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                      2x 2x 2x   2x 1280x 1280x       2x    
import type { Types } from '@cornerstonejs/core';
 
/**
 * Calculates the area of an array of `Point2` points using the shoelace algorithm.
 *
 * The units of the area are in the same units as the points are in. E.g. if
 * the points are in canvas, then the result is in canvas pixels ^2; If they are
 * in mm, then the result is in mm^2; etc.
 */
export default function getArea(points: Types.Point2[]): number {
  // Shoelace algorithm.
  const n = points.length;
  let area = 0.0;
  let j = n - 1;
 
  for (let i = 0; i < n; i++) {
    area += (points[j][0] + points[i][0]) * (points[j][1] - points[i][1]);
    j = i; // j is previous vertex to i
  }
 
  // Return absolute value of half the sum (half as summing up traingles).
  return Math.abs(area / 2.0);
}