-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path9-nodiv.js
71 lines (61 loc) · 1.5 KB
/
9-nodiv.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
'use strict';
class CircularQueueNode {
length = 0;
constructor({ size }) {
this.size = size;
this.buffer = new Array(size);
this.readIndex = 0;
this.writeIndex = 0;
this.next = null;
}
enqueue(item) {
if (this.length === this.size) return false;
this.buffer[this.writeIndex++] = item;
if (this.writeIndex === this.size) this.writeIndex = 0;
this.length++;
return true;
}
dequeue() {
if (this.length === 0) return null;
const item = this.buffer[this.readIndex];
this.buffer[this.readIndex++] = null;
if (this.readIndex === this.size) this.readIndex = 0;
this.length--;
return item;
}
}
class UnrolledQueue {
#length = 0;
#nodeSize = 2048;
#head = null;
#tail = null;
constructor(options = {}) {
const { nodeSize } = options;
if (nodeSize) this.#nodeSize = nodeSize;
const node = new CircularQueueNode({ size: this.#nodeSize });
this.#head = node;
this.#tail = node;
}
get length() {
return this.#length;
}
enqueue(item) {
if (!this.#head.enqueue(item)) {
const node = new CircularQueueNode({ size: this.#nodeSize });
this.#head.next = node;
this.#head = node;
this.#head.enqueue(item);
}
this.#length++;
}
dequeue() {
if (this.#length === 0) return null;
const item = this.#tail.dequeue();
this.#length--;
if (this.#tail.length === 0 && this.#tail.next) {
this.#tail = this.#tail.next;
}
return item;
}
}
module.exports = UnrolledQueue;