all files / src/ point.js

5.26% Statements 1/19
0% Branches 0/8
0% Functions 0/8
5.26% Lines 1/19
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 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85                                                                                                                                                                       
function pageToPoint (e) {
  return {
    x: e.pageX,
    y: e.pageY
  };
}
 
function subtract (lhs, rhs) {
  return {
    x: lhs.x - rhs.x,
    y: lhs.y - rhs.y
  };
}
 
function copy (point) {
  return {
    x: point.x,
    y: point.y
  };
}
 
function distance (from, to) {
  return Math.sqrt(distanceSquared(from, to));
}
 
function distanceSquared (from, to) {
  const delta = subtract(from, to);
 
 
  return delta.x * delta.x + delta.y * delta.y;
}
 
function insideRect (point, rect) {
  if(point.x < rect.left ||
        point.x > rect.left + rect.width ||
        point.y < rect.top ||
        point.y > rect.top + rect.height) {
    return false;
  }
 
  return true;
}
 
/**
 * Returns the closest source point to a target point
 * given an array of source points.
 *
 * @param sources An Array of source Points
 * @param target The target Point
 * @returns Point The closest point from the points array
 */
function findClosestPoint (sources, target) {
  const distances = [];
  let minDistance;
 
  sources.forEach(function (source, index) {
    const d = distance(source, target);
 
    distances.push(d);
 
    if (index === 0) {
      minDistance = d;
    } else {
      minDistance = Math.min(d, minDistance);
    }
  });
 
  const index = distances.indexOf(minDistance);
 
 
  return sources[index];
}
 
const point = {
  subtract,
  copy,
  pageToPoint,
  distance,
  distanceSquared,
  insideRect,
  findClosestPoint
};
 
export default point;