From 92293c66156e49f801fed6e8cc0996fd88f5f33b Mon Sep 17 00:00:00 2001 From: Fuwn Date: Sun, 3 Sep 2023 18:36:53 -0700 Subject: feat(settings): move last prune times to store --- src/stores/lastPruneTimes.ts | 62 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 src/stores/lastPruneTimes.ts (limited to 'src/stores/lastPruneTimes.ts') diff --git a/src/stores/lastPruneTimes.ts b/src/stores/lastPruneTimes.ts new file mode 100644 index 00000000..ef71053b --- /dev/null +++ b/src/stores/lastPruneTimes.ts @@ -0,0 +1,62 @@ +import { browser } from '$app/environment'; +import { writable } from 'svelte/store'; + +interface LastPruneTimes { + anime: number; + chapters: number; + manga: number; +} + +const defaultTimes: LastPruneTimes = { + anime: 1, + chapters: 1, + manga: 1 +}; + +const createStore = () => { + const { subscribe, set, update } = writable( + JSON.parse( + browser + ? localStorage.getItem('lastPruneTimes') ?? JSON.stringify(defaultTimes) + : JSON.stringify(defaultTimes) + ) + ); + let state: LastPruneTimes; + + subscribe((value) => (state = value)); + + return { + subscribe, + set, + update, + reset: () => set(defaultTimes), + get: () => { + const keys = Object.keys(defaultTimes); + const lastPruneTimesKeys = Object.keys(state); + + if (keys.length !== lastPruneTimesKeys.length) { + return defaultTimes; + } + + for (const key of keys) { + if (!lastPruneTimesKeys.includes(key)) { + return defaultTimes; + } + } + + return state; + }, + setKey: (key: keyof LastPruneTimes, value: unknown) => + update((lastPruneTimes) => ({ ...lastPruneTimes, [key]: value })) + }; +}; + +const lastPruneTimes = createStore(); + +lastPruneTimes.subscribe((value) => { + if (browser) { + localStorage.setItem('lastPruneTimes', JSON.stringify(value)); + } +}); + +export default lastPruneTimes; -- cgit v1.2.3