File tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change
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 ( ) ;
You can’t perform that action at this time.
0 commit comments