diff --git a/lib/toGetClosestPoint/index.ts b/lib/toGetClosestPoint/index.ts new file mode 100644 index 0000000..97fec38 --- /dev/null +++ b/lib/toGetClosestPoint/index.ts @@ -0,0 +1,3 @@ +import { toGetClosestPoint } from "./toGetClosestPoint"; + +export default toGetClosestPoint; diff --git a/lib/toGetClosestPoint/toGetClosestPoint.test.ts b/lib/toGetClosestPoint/toGetClosestPoint.test.ts new file mode 100644 index 0000000..e049652 --- /dev/null +++ b/lib/toGetClosestPoint/toGetClosestPoint.test.ts @@ -0,0 +1,36 @@ +import { describe, it, expect } from "vitest"; +import { toGetClosestPoint } from "./toGetClosestPoint.ts"; + +describe("toGetClosestPoint", () => { + it("toGetClosestPoint equale NW", () => { + expect(toGetClosestPoint(-1, -2, 5, 3, -4, 6)).toBe("NW"); + }); + + it("toGetClosestPoint equale N", () => { + expect(toGetClosestPoint(-1, -2, 5, 3, 4, 5)).toBe("N"); + }); + + it("toGetClosestPoint equale NE", () => { + expect(toGetClosestPoint(-1, -2, 5, 3, 9, 3)).toBe("NE"); + }); + + it("toGetClosestPoint equale E", () => { + expect(toGetClosestPoint(-1, -2, 5, 3, 7, 0)).toBe("E"); + }); + + it("toGetClosestPoint equale SE", () => { + expect(toGetClosestPoint(-1, -2, 5, 3, 8, -4)).toBe("SE"); + }); + + it("toGetClosestPoint equale S", () => { + expect(toGetClosestPoint(-1, -2, 5, 3, 2, -4)).toBe("S"); + }); + + it("toGetClosestPoint equale SW", () => { + expect(toGetClosestPoint(-1, -2, 5, 3, -5, -2)).toBe("SW"); + }); + + it("toGetClosestPoint equale W", () => { + expect(toGetClosestPoint(-1, -2, 5, 3, -5, 2)).toBe("W"); + }); +}); diff --git a/lib/toGetClosestPoint/toGetClosestPoint.ts b/lib/toGetClosestPoint/toGetClosestPoint.ts new file mode 100644 index 0000000..4ff41ef --- /dev/null +++ b/lib/toGetClosestPoint/toGetClosestPoint.ts @@ -0,0 +1,66 @@ +type Direction = "N" | "E" | "S" | "W" | "NW" | "NE" | "SW" | "SE"; +export function toGetClosestPoint( + x1: number, + y1: number, + x2: number, + y2: number, + sx: number, + sy: number, +) { + let direction: Direction = "N"; + + const sectors: Record = { + NW: [x1, y2], + N: [x1, y2], + NE: [x2, y2], + E: [x2, y2], + SE: [x2, y1], + S: [x1, y1], + SW: [x1, y1], + W: [x1, y2], + }; + + for (let key in sectors) { + const [x, y] = sectors[key]; + + if (sx <= x && sy >= y) { + direction = "NW"; + break; + } + if (sx >= x && sy > y && sx <= x2) { + direction = "N"; + break; + } + if (sx >= x && sy >= y) { + direction = "NE"; + break; + } + + if (sx >= x && sy <= y && sy >= y1) { + direction = "E"; + break; + } + + if (sx >= x && sy <= y && sx <= x2) { + direction = "S"; + break; + } + + if (sx >= x && sy <= y) { + direction = "SE"; + break; + } + + if (sy <= y && sx <= x) { + direction = "SW"; + break; + } + + if (sy <= y2 && sy >= y1 && sx <= x) { + direction = "W"; + break; + } + } + + return direction; +}