geometry.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. /**
  2. * Calculates the center between a list of points.
  3. *
  4. * @param {array} points A list of points to calculate the center of.
  5. */
  6. var getCenterOfPoints = function getCenterOfPoints(points) {
  7. var sum = points.reduce(function (sum, point) {
  8. sum.x += point.x;
  9. sum.y += point.y;
  10. return sum;
  11. }, { x: 0, y: 0 });
  12. return {
  13. x: sum.x / points.length,
  14. y: sum.y / points.length
  15. };
  16. };
  17. /**
  18. * Calculates the distance between two points based on their x and y
  19. * coordinates.
  20. *
  21. * @param {object} p1 The x and y coordinates of the first point.
  22. * @param {object} p2 The x and y coordinates of the second point.
  23. * @returns {number} Returns the distance between the points.
  24. */
  25. var getDistanceBetweenPoints = function getDistanceBetweenPoints(p1, p2) {
  26. return Math.sqrt(Math.pow(p2.x - p1.x, 2) + Math.pow(p2.y - p1.y, 2));
  27. };
  28. /**
  29. * Calculates the angle between two points.
  30. *
  31. * TODO: add unit tests.
  32. *
  33. * @param {object} p1 The first point.
  34. * @param {object} p2 The second point.
  35. * @returns {number} Returns the angle in radians.
  36. */
  37. var getAngleBetweenPoints = function getAngleBetweenPoints(p1, p2) {
  38. return Math.atan2(p2.x - p1.x, p2.y - p1.y);
  39. };
  40. var geometry = {
  41. getAngleBetweenPoints: getAngleBetweenPoints,
  42. getCenterOfPoints: getCenterOfPoints,
  43. getDistanceBetweenPoints: getDistanceBetweenPoints
  44. };
  45. export default geometry;