-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path4-unrolled.js
73 lines (64 loc) · 1.47 KB
/
4-unrolled.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
'use strict';
class QueueNode {
constructor({ size }) {
this.length = 0;
this.size = size;
this.readIndex = 0;
this.writeIndex = 0;
this.buffer = new Array(size);
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--;
if (this.length === 0) {
this.readIndex = 0;
this.writeIndex = 0;
}
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 QueueNode({ size: this.#nodeSize });
this.#head = node;
this.#tail = node;
}
get length() {
return this.#length;
}
enqueue(item) {
if (!this.#head.enqueue(item)) {
const node = new QueueNode({ 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;