-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathStore.re
43 lines (38 loc) · 1.25 KB
/
Store.re
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
let initialState = Hashtbl.create(128);
let subscribers = Hashtbl.create(128);
let state = initialState;
let subscribe = (~query: string, subscriberCallback: string => unit) => {
switch (Hashtbl.find_opt(subscribers, query)) {
| Some(subscriberCallbacks) =>
Hashtbl.replace(
subscribers,
query,
[subscriberCallback, ...subscriberCallbacks],
)
| None => Hashtbl.add(subscribers, query, [subscriberCallback])
};
/* Return unsubscribe-method */
() =>
switch (Hashtbl.find_opt(subscribers, query)) {
| Some(subscriberCallbacks) =>
let subscribersWithoutCurrentCallback =
subscriberCallbacks
|> List.filter(callback => callback !== subscriberCallback);
Hashtbl.replace(subscribers, query, subscribersWithoutCurrentCallback);
| None => ()
};
};
let publish = (~query: string, value: string) => {
/* Update data in store */
switch (Hashtbl.find_opt(state, query)) {
| Some(_data) => Hashtbl.replace(state, query, value)
| None => Hashtbl.add(state, query, value)
};
/* Notify subscribers */
switch (Hashtbl.find_opt(subscribers, query)) {
| Some(subscriberCallbacks) =>
subscriberCallbacks
|> List.iter(subscriberCallback => subscriberCallback(value))
| None => ()
};
};