File tree Expand file tree Collapse file tree 2 files changed +93
-0
lines changed
Expand file tree Collapse file tree 2 files changed +93
-0
lines changed Original file line number Diff line number Diff line change 1+ 'use strict' ;
2+
3+ class Pool {
4+ constructor ( ) {
5+ this . items = [ ] ;
6+ this . current = 0 ;
7+ }
8+
9+ next ( ) {
10+ const item = this . items [ this . current ] ;
11+ this . current ++ ;
12+ if ( this . current === this . items . length ) this . current = 0 ;
13+ return item ;
14+ }
15+
16+ add ( item ) {
17+ if ( this . items . includes ( item ) ) throw new Error ( 'Pool: add duplicates' ) ;
18+ this . items . push ( item ) ;
19+ }
20+ }
21+
22+ // Usage
23+
24+ const pool = new Pool ( ) ;
25+ pool . add ( { item : 1 } ) ;
26+ pool . add ( { item : 2 } ) ;
27+ pool . add ( { item : 3 } ) ;
28+
29+ for ( let i = 0 ; i < 10 ; i ++ ) {
30+ console . log ( pool . next ( ) ) ;
31+ }
Original file line number Diff line number Diff line change 1+ 'use strict' ;
2+
3+ class Pool {
4+ constructor ( ) {
5+ this . items = [ ] ;
6+ this . free = [ ] ;
7+ this . current = 0 ;
8+ this . size = 0 ;
9+ this . available = 0 ;
10+ }
11+
12+ next ( ) {
13+ if ( this . available === 0 ) return null ;
14+ let item = null ;
15+ let free = false ;
16+ do {
17+ item = this . items [ this . current ] ;
18+ free = this . free [ this . current ] ;
19+ this . current ++ ;
20+ } while ( ! item || ! free ) ;
21+ if ( this . current === this . size ) this . current = 0 ;
22+ return item ;
23+ }
24+
25+ add ( item ) {
26+ if ( this . items . includes ( item ) ) throw new Error ( 'Pool: add duplicates' ) ;
27+ this . size ++ ;
28+ this . available ++ ;
29+ this . items . push ( item ) ;
30+ this . free . push ( true ) ;
31+ }
32+
33+ capture ( ) {
34+ const item = this . next ( ) ;
35+ if ( ! item ) return null ;
36+ const index = this . items . indexOf ( item ) ;
37+ this . free [ index ] = false ;
38+ this . available -- ;
39+ return item ;
40+ }
41+
42+ release ( item ) {
43+ const index = this . items . indexOf ( item ) ;
44+ if ( index < 0 ) throw new Error ( 'Pool: release unexpected item' ) ;
45+ if ( this . free [ index ] ) throw new Error ( 'Pool: release not captured' ) ;
46+ this . free [ index ] = true ;
47+ this . available ++ ;
48+ }
49+ }
50+
51+ // Usage
52+
53+ const pool = new Pool ( ) ;
54+ pool . add ( { item : 1 } ) ;
55+ pool . add ( { item : 2 } ) ;
56+ const last = { item : 3 } ;
57+ pool . add ( last ) ;
58+
59+ for ( let i = 0 ; i < 10 ; i ++ ) {
60+ console . log ( pool . capture ( ) ) ;
61+ if ( i === 5 ) pool . release ( last ) ;
62+ }
You can’t perform that action at this time.
0 commit comments