-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy path7-buffer.js
More file actions
49 lines (39 loc) · 1.04 KB
/
7-buffer.js
File metadata and controls
49 lines (39 loc) · 1.04 KB
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
'use strict';
const duplicate = (factory, n) => new Array(n).fill(null).map(factory);
const poolify = (factory, { size, max }) => {
let allocated = size;
const instances = duplicate(factory, size);
const acquire = () => {
if (instances.length === 0 && allocated < max) {
const grow = Math.min(max - allocated, size - instances.length);
allocated += grow;
const addition = duplicate(factory, grow);
instances.push(...addition);
}
const instance = instances.pop();
return instance;
};
const release = (instance) => {
if (instances.length < max) {
instances.push(instance);
}
};
return { acquire, release };
};
const factorify =
(Category, ...args) =>
() =>
new Category(...args);
// Usage
const factory = factorify(Uint32Array, 1024);
const pool = poolify(factory, { size: 10, max: 13 });
let i = 0;
const next = () => {
const instance = pool.acquire();
i++;
if (i < 20) {
setTimeout(next, i * 10);
setTimeout(() => pool.release(instance), i * 100);
}
};
next();