-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCozyPorts.alpha.ts
56 lines (46 loc) · 1.37 KB
/
CozyPorts.alpha.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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
export default class CozyPorts {
private _listeners: [any?][] = [];
private _dataBus: [any?][] = [];
private _numberOfPorts: number;
public constructor(numberOfPorts: number)
{
this._numberOfPorts = numberOfPorts;
if (numberOfPorts === 0)
{
throw new Error(`At least one port shoud be created`);
};
for (let i = 0; i < this._numberOfPorts ; ++i)
{
this._dataBus.push([]);
};
};
public connectToPort(port: number, entity: any)
{
if (port >= this._numberOfPorts)
{
throw new Error(`Port number ${port} can't be used. Available port numbers are: ${0 - --this._numberOfPorts}`)
};
this._dataBus[port].push(entity);
this._listeners.push(entity);
const message = (message: string, data?: any) => {
this.dispatch(port, message, data)
};
return { port: port, message};
};
public toAll(message: string, data?: any)
{
this._listeners.forEach((value) => {
try {
value[message](data);
} catch(e) {}
});
};
private dispatch(port: number, message: string, data?: string)
{
this._dataBus[port].forEach((value) => {
try {
value[message](data);
} catch(e) {}
});
};
};