-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy path2-drain.js
More file actions
41 lines (30 loc) · 795 Bytes
/
2-drain.js
File metadata and controls
41 lines (30 loc) · 795 Bytes
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
'use strict';
const POOL_SIZE = 5;
const poolify = (factory) => {
const instances = new Array(POOL_SIZE).fill(null).map(factory);
const acquire = () => {
const instance = instances.pop() || factory();
console.log('Get from pool, count =', instances.length);
return instance;
};
const release = (instance) => {
instances.push(instance);
console.log('Recycle item, count =', instances.length);
};
return { acquire, release };
};
class Connection {
static index = 0;
constructor(url) {
this.url = url;
}
static create() {
return new Connection(`http://10.0.0.1/${Connection.index++}`);
}
}
// Usage
const pool = poolify(Connection.create);
for (let i = 0; i < 10; i++) {
const connection = pool.acquire();
console.log(connection);
}