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
class ArrayQueue<T extends () => Promise<void>> {
private arr: T[]
private isRunning: boolean
private isSuspended: boolean
constructor() {
this.arr = []
this.isRunning = false
this.isSuspended = false
}

private consumeFunc = async (queueItme: T) => {
await queueItme()
}

get isEmpty() {
return this.arr.length === 0
}

private consume = async () => {
if (!this.isRunning && !this.isSuspended && !this.isEmpty) {
this.isRunning = true
try {
await this.consumeFunc(this.getFront())
this.pop()
this.isRunning = false
this.consume()
} catch (err) {
log.error(err.message)
}
}
}

push = (element: T) => {
this.arr.push(element)
this.consume()
return true
}
pop = () => {
return this.arr.shift()
}
getFront = () => {
return this.arr[0]
}
getRear = () => {
return this.arr[this.arr.length - 1]
}
clear = () => {
this.arr = []
}
size = () => {
return this.arr.length
}
suspend = () => {
this.isSuspended = true
}
start = () => {
this.isSuspended = false
this.consume()
}
}