File size: 1,541 Bytes
6f9647d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
// Simple Store using Map
class OfflineStore {
  state: Map<any, any>;
  subscribers: Set<(state: any) => void>;

  constructor() {
    this.state = new Map();
    this.subscribers = new Set();
  }

  // Get a value by key
  get(key: string) {
    return this.state.get(key);
  }

  // Set a value by key and notify subscribers
  set(key: string, value: any) {
    this.state.set(key, value);
    this.notifySubscribers();
  }

  // Delete a value by key and notify subscribers
  delete(key: string) {
    this.state.delete(key);
    this.notifySubscribers();
  }

  // Clear the entire store and notify subscribers
  clear() {
    this.state.clear();
    this.notifySubscribers();
  }

  // Subscribe to store changes
  subscribe(callback: (state: any) => void) {
    this.subscribers.add(callback);
    return () => this.subscribers.delete(callback);
  }

  // Notify all subscribers
  notifySubscribers() {
    this.subscribers.forEach((callback) => {
      return callback(this.state);
    });
  }
}

const offline_store = new OfflineStore();

export { offline_store };

// Example usage
// Subscribe to changes
// const unsubscribe = store.subscribe((state: any[]) => {
//   console.log("Store updated:", Array.from(state.entries()));
// });

// Set values
// store.set("user", { name: "Alice", age: 30 });
// store.set("theme", "dark");

// Get a value
// console.log(store.get("user")); // { name: "Alice", age: 30 }

// Delete a value
// store.delete("theme");

// Clear the store
// store.clear();

// Unsubscribe
// unsubscribe();