Skip to content

Commit

Permalink
ENH: rewritten checkpoint.ts to use a custom solution instead of svel…
Browse files Browse the repository at this point in the history
…te-persistent-store for a reduction from 15Kb to less than 1Kb
  • Loading branch information
LyonSyonII committed Dec 19, 2023
1 parent f6d1af9 commit 564f52c
Showing 1 changed file with 38 additions and 7 deletions.
45 changes: 38 additions & 7 deletions frontend/src/components/Checkpoint/checkpoint.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,45 @@
import { writable } from "@macfja/svelte-persistent-store";
type Checkpoints = Map<string, Set<string>>

const checkpointStore = writable("checkpoints", new Map<string, Set<string>>());
class Persistent {
persistent: Checkpoints = new Map<string, Set<string>>();
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];
if (k === undefined) {
throw "Invalid id";
}

checkpointStore.update((checkpoints) => {
persistentCheckpoints.update((checkpoints) => {
const checkpoint = checkpoints.get(k);
if (checkpoint === undefined) {
checkpoints.set(k, new Set([id]));
Expand All @@ -24,11 +55,11 @@ export function subscribe(id: string, run: (checkpoint: Set<string>) => 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<string>);
});
}
Expand All @@ -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;
});
}
}

0 comments on commit 564f52c

Please sign in to comment.