Skip to content

Commit 0404564

Browse files
committed
ensure that items are not enqueued twice
Use nice SetIterator trick
1 parent 37cc6f4 commit 0404564

File tree

1 file changed

+11
-39
lines changed

1 file changed

+11
-39
lines changed

lib/util/Queue.js

Lines changed: 11 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -2,50 +2,22 @@
22

33
module.exports = class Queue {
44
constructor(items) {
5-
this.first = null;
6-
this.last = null;
7-
this.recycle = [];
8-
this.length = 0;
9-
if(items) {
10-
for(const item of items) {
11-
this.enqueue(item);
12-
}
13-
}
5+
this.set = new Set(items);
6+
this.iterator = this.set[Symbol.iterator]();
7+
}
8+
9+
get length() {
10+
return this.set.size;
1411
}
1512

1613
enqueue(item) {
17-
const first = this.first;
18-
let node;
19-
if(this.recycle.length > 0) {
20-
node = this.recycle.pop();
21-
node.item = item;
22-
node.next = null;
23-
} else {
24-
node = {
25-
item,
26-
next: null
27-
};
28-
}
29-
if(first === null) {
30-
this.last = node;
31-
} else {
32-
first.next = node;
33-
}
34-
this.first = node;
35-
this.length++;
14+
this.set.add(item);
3615
}
3716

3817
dequeue() {
39-
const last = this.last;
40-
if(last === null)
41-
return undefined;
42-
const next = last.next;
43-
if(next === null) {
44-
this.first = null;
45-
}
46-
this.last = next;
47-
this.length--;
48-
this.recycle.push(last);
49-
return last.item;
18+
const result = this.iterator.next();
19+
if(result.done) return undefined;
20+
this.set.delete(result.value);
21+
return result.value;
5022
}
5123
};

0 commit comments

Comments
 (0)