-
Notifications
You must be signed in to change notification settings - Fork 42
/
Copy patharray_queue.js
60 lines (51 loc) · 1.24 KB
/
array_queue.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 {
constructor() {
this.storage = [];
this.head = 0;
this.tail = 0;
// Number of cancelled elements between head and tail
this.cancelCount = 0;
}
enqueue(element) {
const ticket = this.tail;
this.storage[this.tail] = element;
this.tail += 1;
return ticket;
}
cancel(ticket) {
if (this.storage[ticket] !== undefined) {
this.storage[ticket] = undefined;
this.cancelCount += 1;
}
}
dequeue() {
// skip cancelled elements at the front of the queue
while (this.head < this.tail &&
this.storage[this.head] === undefined) {
this.head += 1;
this.cancelCount -= 1;
}
if (this.head === this.tail) {
return undefined;
}
const element = this.storage[this.head];
this.storage[this.head] = undefined;
this.head += 1;
return element;
}
count() {
return this.tail - this.head - this.cancelCount;
}
forEach(callback) {
let skipCount = 0;
for (let i = this.head; i < this.tail; i += 1) {
if (this.storage[i] === undefined) {
skipCount += 1;
continue;
}
const index = i - this.head - skipCount;
callback(this.storage[i], index, this);
}
}
}
export default ArrayQueue;