point.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /**
  2. * This class is responsible for storing point in 2D.
  3. */
  4. export class point {
  5. #x;
  6. #y;
  7. /**
  8. * This create new point, can be setup by new position.
  9. *
  10. * @param {number} x - X position
  11. * @param {number} y - Y position
  12. */
  13. constructor(x = 0, y = 0) {
  14. this.#x = x;
  15. this.#y = y;
  16. }
  17. /**
  18. * @returns {number} - X value of point
  19. */
  20. get x() {
  21. return this.#x;
  22. }
  23. /**
  24. * @returns {number} - Y value of point
  25. */
  26. get y() {
  27. return this.#y;
  28. }
  29. /**
  30. * @param {number} target - New X value
  31. */
  32. set x(target) {
  33. this.#x = target;
  34. }
  35. /**
  36. * @param {number} target - New Y value
  37. */
  38. set y(target) {
  39. this.#y = target;
  40. }
  41. /**
  42. * This compare two points, and return compare result.
  43. *
  44. * @example (point(5, 4).compare(point(10, 10)) => point(5, 6))
  45. * @param {point} target - Point to calculate
  46. * @returns {point} - Compare result
  47. */
  48. compare(target) {
  49. return new point(
  50. target.x - this.x,
  51. target.y - this.y
  52. );
  53. }
  54. /**
  55. * This calculate distance between two points.
  56. *
  57. * @param {point} target - Second point to calculate distance between
  58. * @returns {number} - Distance between this point and given point
  59. */
  60. distance(target) {
  61. const compared = this.compare(target);
  62. const summary = Math.pow(compared.x, 2) + Math.pow(compared.y, 2);
  63. const result = Math.sqrt(summary);
  64. return result;
  65. }
  66. }