aboutsummaryrefslogtreecommitdiff
path: root/src/stores/lastPruneTimes.ts
blob: 9c4afc5b8b0818e934212aa9440dae43aeb8767d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
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<LastPruneTimes>(
    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;