All files / packages/tools/src/utilities/math/vec2 findClosestPoint.ts

100% Statements 11/11
100% Branches 2/2
100% Functions 3/3
100% Lines 11/11

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 35 36 37 38 39 40 41                          113x 113x   113x 412x   412x 218x 218x       113x                   412x 412x   412x    
import type { Types } from '@cornerstonejs/core';
 
/**
 * Find the closest point to the target point
 *
 * @param sourcePoints - The potential source points.
 * @param targetPoint - The target point, used to find the closest source.
 * @returns The closest point in the array of point sources
 */
export default function findClosestPoint(
  sourcePoints: Array<Types.Point2>,
  targetPoint: Types.Point2
): Types.Point2 {
  let minPoint = [0, 0];
  let minDistance = Number.MAX_SAFE_INTEGER;
 
  sourcePoints.forEach(function (sourcePoint) {
    const distance = _distanceBetween(targetPoint, sourcePoint);
 
    if (distance < minDistance) {
      minDistance = distance;
      minPoint = [...sourcePoint];
    }
  });
 
  return minPoint as Types.Point2;
}
 
/**
 *
 * @private
 * @param p1
 * @param p2
 */
function _distanceBetween(p1: Types.Point2, p2: Types.Point2): number {
  const [x1, y1] = p1;
  const [x2, y2] = p2;
 
  return Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2));
}