-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchannels.js
63 lines (58 loc) · 1.36 KB
/
channels.js
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
export function createChannels() {
const sinks = new Map();
const createSink = () => {
const reference = {};
sinks.set(reference, new Map());
return {
on(key, listener) {
const sink = sinks.get(reference);
if (sink.has(key)) {
sink.get(key).push(listener);
} else {
sink.set(key, [listener]);
}
},
emit(key, ...args) {
const sink = sinks.get(reference);
const channels = sink.get(key);
if (Array.isArray(channels)) {
channels.forEach((channel) => {
channel(...args);
});
}
},
};
};
const send = (id, event, ...args) => {
const sink = sinks.get(id);
const listeners = sink.get(event);
listeners.forEach((listener) => {
listener(...args);
});
};
const sendToSink = (cb) => {
cb([...sinks.keys()], send);
};
const events = new Map();
return {
createSink,
sendToSink,
source: {
on(key, listener) {
if (events.has(key)) {
events.get(key).push(listener);
} else {
events.set(key, [listener]);
}
},
emit(key, ...args) {
sinks.forEach((sink) => {
const listeners = sink.get(key);
listeners.forEach((listener) => {
listener(...args);
});
});
},
},
};
}