-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path7-current.js
98 lines (84 loc) · 1.94 KB
/
7-current.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
'use strict';
class QueueNode {
length = 0;
constructor({ size }) {
this.size = size;
this.buffer = new Array(size);
this.reset();
}
reset() {
this.readIndex = 0;
this.writeIndex = 0;
this.next = null;
}
enqueue(item) {
if (this.writeIndex >= this.size) return false;
this.buffer[this.writeIndex++] = item;
this.length++;
return true;
}
dequeue() {
if (this.length === 0) return null;
const index = this.readIndex++;
const item = this.buffer[index];
this.buffer[index] = null;
this.length--;
return item;
}
}
class UnrolledQueue {
#length = 0;
#nodeSize = 1024;
#poolSize = 2;
#head = null;
#tail = null;
#current = null;
constructor(options = {}) {
const { nodeSize, poolSize } = options;
if (nodeSize) this.#nodeSize = nodeSize;
if (poolSize) this.#poolSize = poolSize;
const first = this.#createNode();
let node = first;
for (let i = 1; i < this.#poolSize; i++) {
node.next = this.#createNode();
node = node.next;
}
this.#head = node;
this.#current = first;
this.#tail = first;
}
#createNode() {
return new QueueNode({ size: this.#nodeSize });
}
get length() {
return this.#length;
}
enqueue(item) {
if (!this.#current.enqueue(item)) {
if (this.#current === this.#head) {
const node = this.#createNode();
this.#current.next = node;
this.#current = node;
this.#head = node;
} else {
this.#current = this.#current.next;
}
this.#current.enqueue(item);
}
this.#length++;
}
dequeue() {
if (this.#length === 0) return null;
const node = this.#tail;
const item = node.dequeue();
this.#length--;
if (node.length === 0 && node !== this.#current) {
this.#tail = node.next;
node.reset();
this.#head.next = node;
this.#head = node;
}
return item;
}
}
module.exports = UnrolledQueue;