-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
73 lines (48 loc) · 1.16 KB
/
index.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";
const EventEmitter = require("events");
class ObjectPool {
constructor(factoryFunction) {
this.factory = factoryFunction;
this.objects = new Set();
this.events = new EventEmitter();
}
get size() {
return this.objects.size;
}
set size(size = 0) {
if (typeof size !== "number") {
throw new Error("Parameter is not a number: " + typeof size);
}
let current = this.objects.size;
while (current < size) {
const object = this.factory();
this.put(object);
current++;
}
while (current > size) {
const [object] = this.objects.values();
this.delete(object);
current--;
}
}
get() {
if (this.size === 0) {
const object = this.factory();
this.events.emit("get", object);
return object;
}
const [object] = this.objects.values();
this.objects.delete(object);
this.events.emit("get", object);
return object;
}
put(object) {
this.objects.add(object);
this.events.emit("put", object);
}
delete(object) {
this.objects.delete(object);
this.events.emit("delete", object);
}
}
module.exports = ObjectPool;