-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path6-pool.js
100 lines (86 loc) · 2 KB
/
6-pool.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
99
100
'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 Pool {
constructor(count, factory) {
const instances = new Array(count);
for (let i = 0; i < count; i++) instances[i] = factory();
this.count = count;
this.instances = instances;
this.factory = factory;
}
acquire() {
const instance = this.instances.shift() || this.factory();
return instance;
}
release(instance) {
const { instances, count } = this;
if (instances.length < count) instances.push(instance);
}
}
class UnrolledQueue {
#length = 0;
#head = null;
#tail = null;
#pool = null;
constructor(options = {}) {
const { nodeSize = 1024, poolSize = 2 } = options;
const pool = new Pool(poolSize, () => new QueueNode({ size: nodeSize }));
this.#pool = pool;
const node = pool.acquire();
this.#head = node;
this.#tail = node;
}
get length() {
return this.#length;
}
enqueue(item) {
if (!this.#head.enqueue(item)) {
const node = this.#pool.acquire();
this.#head.next = node;
this.#head = node;
this.#head.enqueue(item);
}
this.#length++;
}
dequeue() {
if (this.#length === 0) return null;
const tail = this.#tail;
const item = tail.dequeue();
this.#length--;
if (tail.length > 0) return item;
const next = this.#tail.next;
if (next) {
this.#tail = next;
this.#pool.release(tail);
}
tail.reset();
return item;
}
}
module.exports = UnrolledQueue;