-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstore.singleton.ts
34 lines (28 loc) · 994 Bytes
/
store.singleton.ts
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
// -- Singleton Pattern 2 (modular and functional design) -- //
// This approach is more composible and allows tree-shaking unlike OOP based approach
type Listener<T> = (state: T, prevState: T) => void;
// Factory Interface
export type Store<T> = {
getState(): T;
setState(state: Partial<T>): void;
subscribe(listener: Listener<T>): () => void;
};
// Factory to create store
export function createStore<T>(initialState: T): Store<T> {
let state = { ...initialState };
const listeners: Listener<T>[] = [];
const getState = () => ({ ...state });
const setState = (newState: Partial<T>) => {
const prevState = state;
state = { ...state, ...newState };
listeners.forEach(listener => listener(state, prevState));
};
const subscribe = (listener: Listener<T>) => {
listeners.push(listener);
return () => {
const idx = listeners.indexOf(listener);
if (idx > -1) listeners.splice(idx, 1);
};
};
return { getState, setState, subscribe };
}