forked from ant-design/ant-design
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreateStore.tsx
More file actions
39 lines (33 loc) · 758 Bytes
/
createStore.tsx
File metadata and controls
39 lines (33 loc) · 758 Bytes
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
export interface Store {
setState: (partial: Object) => void;
getState: () => any;
subscribe: (listener: () => void) => () => void;
}
export default function createStore(initialState: object): Store {
let state = initialState;
const listeners: any[] = [];
function setState(partial: object) {
state = {
...state,
...partial,
};
for (let i = 0; i < listeners.length; i++) {
listeners[i]();
}
}
function getState() {
return state;
}
function subscribe(listener: () => any) {
listeners.push(listener);
return function unsubscribe() {
const index = listeners.indexOf(listener);
listeners.splice(index, 1);
};
}
return {
setState,
getState,
subscribe,
};
}