From 564f52cf6619eb22dfedf6c135584a05515e899d Mon Sep 17 00:00:00 2001 From: lyonsyonii Date: Tue, 19 Dec 2023 12:23:12 +0100 Subject: [PATCH] ENH: rewritten checkpoint.ts to use a custom solution instead of svelte-persistent-store for a reduction from 15Kb to less than 1Kb --- .../src/components/Checkpoint/checkpoint.ts | 45 ++++++++++++++++--- 1 file changed, 38 insertions(+), 7 deletions(-) diff --git a/frontend/src/components/Checkpoint/checkpoint.ts b/frontend/src/components/Checkpoint/checkpoint.ts index c860765..5af57ad 100644 --- a/frontend/src/components/Checkpoint/checkpoint.ts +++ b/frontend/src/components/Checkpoint/checkpoint.ts @@ -1,6 +1,37 @@ -import { writable } from "@macfja/svelte-persistent-store"; +type Checkpoints = Map> -const checkpointStore = writable("checkpoints", new Map>()); +class Persistent { + persistent: Checkpoints = new Map>(); + subscribers: Array<(checkpoints: Checkpoints) => void> = []; + + constructor() { + this.persistent = this.deserialize(); + } + + private serialize() { + const serialized: Array<[string, string[]]> = [...this.persistent.entries()].map(([k, v]) => [k, Array.from(v)]); + localStorage.setItem("checkpoints", JSON.stringify(serialized)); + } + + private deserialize(): Checkpoints { + const item = localStorage.getItem("checkpoints") as string; + const parsed: Array<[string, string[]]> = item && JSON.parse(item) || []; + return new Map(parsed.map(([k, v]) => [k, new Set(v)])); + } + + update(callback: (checkpoints: Checkpoints) => Checkpoints) { + this.persistent = callback(this.persistent); + this.serialize(); + this.subscribers.forEach((subscriber) => subscriber(this.persistent)); + } + + subscribe(callback: (checkpoints: Checkpoints) => void) { + this.subscribers.push(callback); + callback(this.persistent); + } +} + +const persistentCheckpoints = new Persistent(); export function add(id: string) { const k = id.split("-")[0]; @@ -8,7 +39,7 @@ export function add(id: string) { throw "Invalid id"; } - checkpointStore.update((checkpoints) => { + persistentCheckpoints.update((checkpoints) => { const checkpoint = checkpoints.get(k); if (checkpoint === undefined) { checkpoints.set(k, new Set([id])); @@ -24,11 +55,11 @@ export function subscribe(id: string, run: (checkpoint: Set) => void) { if (k === undefined) { throw "Invalid id"; } - checkpointStore.update( + persistentCheckpoints.update( (checkpoints) => (!checkpoints.has(k) && checkpoints.set(k, new Set([]))) || checkpoints, ); - checkpointStore.subscribe((checkpoints) => { + persistentCheckpoints.subscribe((checkpoints) => { run(checkpoints.get(k) as Set); }); } @@ -38,8 +69,8 @@ export function remove(id: string) { if (k === undefined) { throw "Invalid id"; } - checkpointStore.update((checkpoints) => { + persistentCheckpoints.update((checkpoints) => { checkpoints.delete(k); return checkpoints; }); -} +} \ No newline at end of file