1
1
'use strict' ;
2
2
3
- const poolify = ( factory , min , norm , max ) => {
4
-
5
- const duplicate = n => new Array ( n ) . fill ( ) . map ( ( ) => factory ( ) ) ;
3
+ const duplicate = ( factory , n ) => (
4
+ new Array ( n ) . fill ( ) . map ( ( ) => factory ( ) )
5
+ ) ;
6
6
7
+ const poolify = ( factory , min , norm , max ) => {
8
+ let allocated = norm ;
7
9
const pool = ( par ) => {
8
10
if ( typeof ( par ) !== 'function' ) {
9
11
if ( pool . items . length < max ) {
10
12
const delayed = pool . delayed . pop ( ) ;
11
13
if ( delayed ) {
12
- console . log ( 'Recycle item, pass to delayed' ) ;
14
+ console . log ( 'Recycle item, pass to delayed' , pool . items . length ) ;
13
15
delayed ( par ) ;
14
- return ;
15
16
} else {
17
+ console . log ( 'Recycle item, add to pool' , pool . items . length ) ;
16
18
pool . items . push ( par ) ;
17
19
}
18
20
}
19
- console . log ( 'Recycle item, count =' , pool . items . length ) ;
20
21
return ;
21
22
}
22
- if ( pool . items . length < min ) {
23
- const items = duplicate ( norm - pool . items . length ) ;
23
+ if ( pool . items . length < min && allocated < max ) {
24
+ const grow = Math . min ( max - allocated , norm - pool . items . length ) ;
25
+ allocated += grow ;
26
+ const items = duplicate ( factory , grow ) ;
24
27
pool . items . push ( ...items ) ;
25
28
}
26
29
const res = pool . items . pop ( ) ;
27
- console . log ( 'Get from pool, count =' , pool . items . length ) ;
28
30
if ( res ) {
31
+ console . log ( 'Get from pool, pass to callback' , pool . items . length ) ;
29
32
par ( res ) ;
30
33
} else {
34
+ console . log ( 'Get from pool, add callback to queue' , pool . items . length ) ;
31
35
pool . delayed . push ( par ) ;
32
- console . log ( 'Request delayed' ) ;
33
36
}
34
- return pool ;
35
37
} ;
36
-
37
38
return Object . assign ( pool , {
38
- items : duplicate ( norm ) ,
39
+ items : duplicate ( factory , norm ) ,
39
40
delayed : [ ]
40
41
} ) ;
41
-
42
42
} ;
43
43
44
44
// Usage
@@ -47,15 +47,14 @@ const poolify = (factory, min, norm, max) => {
47
47
const buffer = ( ) => new Uint32Array ( 128 ) ;
48
48
49
49
// Allocate pool of 10 buffers
50
- const pool = poolify ( buffer , 0 , 5 , 10 ) ;
50
+ const pool = poolify ( buffer , 3 , 5 , 7 ) ;
51
51
52
52
let i = 0 ;
53
53
54
54
const next = ( ) => {
55
55
pool ( item => {
56
- console . log ( 'Buffer size' , item . length * 32 ) ;
57
56
i ++ ;
58
- if ( i < 10 ) {
57
+ if ( i < 20 ) {
59
58
setTimeout ( next , i * 10 ) ;
60
59
setTimeout ( ( ) => pool ( item ) , i * 100 ) ;
61
60
}
0 commit comments