From cfd970e21663c3278f6e01d356690789225b6b56 Mon Sep 17 00:00:00 2001 From: Elizabeth Hunt Date: Sat, 2 Dec 2023 14:16:56 -0700 Subject: 2022 day 9 and add utils --- utils/index.ts | 2 ++ utils/jsonds.ts | 66 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ utils/point2d.ts | 9 ++++++++ 3 files changed, 77 insertions(+) create mode 100644 utils/index.ts create mode 100644 utils/jsonds.ts create mode 100644 utils/point2d.ts (limited to 'utils') diff --git a/utils/index.ts b/utils/index.ts new file mode 100644 index 0000000..b2e38c1 --- /dev/null +++ b/utils/index.ts @@ -0,0 +1,2 @@ +export * from "./jsonds"; +export * from "./point2d"; diff --git a/utils/jsonds.ts b/utils/jsonds.ts new file mode 100644 index 0000000..c717232 --- /dev/null +++ b/utils/jsonds.ts @@ -0,0 +1,66 @@ +export class JSONSet { + private items: Set; + + constructor() { + this.items = new Set(); + } + + add(item: T): void { + const itemJson = JSON.stringify(item, Object.keys(item).sort()); + this.items.add(itemJson); + } + + has(item: T): boolean { + const itemJson = JSON.stringify(item, Object.keys(item).sort()); + return this.items.has(itemJson); + } + + delete(item: T): boolean { + const itemJson = JSON.stringify(item, Object.keys(item).sort()); + return this.items.delete(itemJson); + } + + clear(): void { + this.items.clear(); + } + + get size(): number { + return this.items.size; + } +} + +export class JSONHashMap { + private map: Map; + + constructor() { + this.map = new Map(); + } + + set(key: T, value: T): void { + const keyJson = JSON.stringify(key, Object.keys(key).sort()); + this.map.set(keyJson, value); + } + + get(key: T): T | undefined { + const keyJson = JSON.stringify(key, Object.keys(key).sort()); + return this.map.get(keyJson); + } + + has(key: T): boolean { + const keyJson = JSON.stringify(key, Object.keys(key).sort()); + return this.map.has(keyJson); + } + + delete(key: T): boolean { + const keyJson = JSON.stringify(key, Object.keys(key).sort()); + return this.map.delete(keyJson); + } + + clear(): void { + this.map.clear(); + } + + get size(): number { + return this.map.size; + } +} diff --git a/utils/point2d.ts b/utils/point2d.ts new file mode 100644 index 0000000..3d07569 --- /dev/null +++ b/utils/point2d.ts @@ -0,0 +1,9 @@ +export type Vec2 = { + x: number; + y: number; +}; + +export const l2Norm = (p1: Vec2, p2: Vec2) => + Math.sqrt(Math.pow(p2.x - p1.x, 2) + Math.pow(p2.y - p1.y, 2)); + +export const isDiagAdj = (p1: Vec2, p2: Vec2) => l2Norm(p1, p2) <= Math.sqrt(2); -- cgit v1.2.3-70-g09d2