Skip to content

Commit 9edaf8f

Browse files
committed
Add bad example
1 parent 7c11153 commit 9edaf8f

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

JavaScript/4-bad.js

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
'use strict';
2+
3+
const poolify = (factory, min, norm, max) => {
4+
const duplicate = (n) => new Array(n).fill().map(() => factory());
5+
const items = duplicate(norm);
6+
7+
return (item) => {
8+
if (item) {
9+
if (items.length < max) {
10+
items.push(item);
11+
}
12+
console.log('Recycle item, count =', items.length);
13+
return null;
14+
}
15+
if (items.length < min) {
16+
const instances = duplicate(norm - items.length);
17+
items.push(...instances);
18+
}
19+
const res = items.pop();
20+
console.log('Get from pool, count =', items.length);
21+
return res;
22+
};
23+
};
24+
25+
// Usage
26+
27+
// Factory to allocate 4kb buffer
28+
const buffer = () => new Uint32Array(1024);
29+
30+
// Allocate pool of 10 buffers
31+
const pool = poolify(buffer, 5, 10, 15);
32+
33+
let i = 0;
34+
35+
const next = () => {
36+
const item = pool();
37+
console.log('Buffer size', item.length * 32);
38+
i++;
39+
if (i < 20) {
40+
setTimeout(next, i * 10);
41+
setTimeout(() => pool(item), i * 100);
42+
}
43+
};
44+
45+
next();

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy