line.ts 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import { pointCenter, pointRotateRads } from "./point";
  2. import type { GlobalPoint, Line, LocalPoint, Radians } from "./types";
  3. /**
  4. * Create a line from two points.
  5. *
  6. * @param points The two points lying on the line
  7. * @returns The line on which the points lie
  8. */
  9. export function line<P extends GlobalPoint | LocalPoint>(a: P, b: P): Line<P> {
  10. return [a, b] as Line<P>;
  11. }
  12. /**
  13. * Convenient point creation from an array of two points.
  14. *
  15. * @param param0 The array with the two points to convert to a line
  16. * @returns The created line
  17. */
  18. export function lineFromPointPair<P extends GlobalPoint | LocalPoint>([a, b]: [
  19. P,
  20. P,
  21. ]): Line<P> {
  22. return line(a, b);
  23. }
  24. /**
  25. * TODO
  26. *
  27. * @param pointArray
  28. * @returns
  29. */
  30. export function lineFromPointArray<P extends GlobalPoint | LocalPoint>(
  31. pointArray: P[],
  32. ): Line<P> | undefined {
  33. return pointArray.length === 2
  34. ? line<P>(pointArray[0], pointArray[1])
  35. : undefined;
  36. }
  37. // return the coordinates resulting from rotating the given line about an origin by an angle in degrees
  38. // note that when the origin is not given, the midpoint of the given line is used as the origin
  39. export const lineRotate = <Point extends LocalPoint | GlobalPoint>(
  40. l: Line<Point>,
  41. angle: Radians,
  42. origin?: Point,
  43. ): Line<Point> => {
  44. return line(
  45. pointRotateRads(l[0], origin || pointCenter(l[0], l[1]), angle),
  46. pointRotateRads(l[1], origin || pointCenter(l[0], l[1]), angle),
  47. );
  48. };