-
Notifications
You must be signed in to change notification settings - Fork 0
/
asyncQueue.js
52 lines (51 loc) · 1.2 KB
/
asyncQueue.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
'use strict';
const ChannelClosed = { name: 'Channel closed event'};
class Channel {
constructor() {
this.sources = [];
this.sinks = [];
this.opened = true;
}
push(el) {
return new Promise((resolve, reject) => {
if (this.sinks.length) {
const sink = this.sinks.shift();
resolve();
sink.resolver(el);
} else {
this.sources.push({resolver: resolve, rejecter: reject, el: el});
}
});
}
pull() {
return new Promise((resolve) => {
if (this.sources.length) {
const source = this.sources.shift();
source.resolver();
resolve(source.el);
} else {
this.sinks.push({resolver: resolve});
}
});
}
close() {
this.opened = false;
for (let i = 0; i < this.sinks.length; ++i) {
const sink = this.sinks[i];
sink.resolver(Channel.channelClosedEvent());
}
this.sinks = []
for (let i = 0; i < this.sources.length; ++i) {
const source = this.sources[i];
source.rejecter(Channel.channelClosedEvent());
}
this.sources = [];
}
isOpen() {
return this.opened;
}
static channelClosedEvent() {
return ChannelClosed;
}
}
module.exports = Channel;