File tree 3 files changed +103
-0
lines changed
3 files changed +103
-0
lines changed Original file line number Diff line number Diff line change
1
+ interface UnrolledQueueOptions {
2
+ nodeSize ?: number ;
3
+ }
4
+
5
+ declare class UnrolledQueue < T = any > {
6
+ constructor ( options ?: UnrolledQueueOptions ) ;
7
+
8
+ readonly length : number ;
9
+
10
+ enqueue ( item : T ) : void ;
11
+ dequeue ( ) : T | null ;
12
+ }
Original file line number Diff line number Diff line change
1
+ 'use strict' ;
2
+
3
+ class QueueNode {
4
+ constructor ( { size } ) {
5
+ this . length = 0 ;
6
+ this . size = size ;
7
+ this . readIndex = 0 ;
8
+ this . writeIndex = 0 ;
9
+ this . buffer = new Array ( size ) ;
10
+ this . next = null ;
11
+ }
12
+
13
+ enqueue ( item ) {
14
+ if ( this . length === this . size ) return false ;
15
+ this . buffer [ this . writeIndex ++ ] = item ;
16
+ this . length ++ ;
17
+ return true ;
18
+ }
19
+
20
+ dequeue ( ) {
21
+ if ( this . length === 0 ) return null ;
22
+ const item = this . buffer [ this . readIndex ++ ] ;
23
+ this . length -- ;
24
+ return item ;
25
+ }
26
+ }
27
+
28
+ class UnrolledQueue {
29
+ #length = 0 ;
30
+ #nodeSize = 2048 ;
31
+ #head = null ;
32
+ #tail = null ;
33
+
34
+ constructor ( options = { } ) {
35
+ const { nodeSize } = options ;
36
+ if ( nodeSize ) this . #nodeSize = nodeSize ;
37
+ const node = new QueueNode ( { size : nodeSize } ) ;
38
+ this . #head = node ;
39
+ this . #tail = node ;
40
+ }
41
+
42
+ get length ( ) {
43
+ return this . #length;
44
+ }
45
+
46
+ enqueue ( item ) {
47
+ if ( ! this . #head. enqueue ( item ) ) {
48
+ const node = new QueueNode ( { size : this . #nodeSize } ) ;
49
+ this . #head. next = node ;
50
+ this . #head = node ;
51
+ this . #head. enqueue ( item ) ;
52
+ }
53
+ this . #length++ ;
54
+ }
55
+
56
+ dequeue ( ) {
57
+ const item = this . #tail. dequeue ( ) ;
58
+ if ( item !== null ) {
59
+ this . #length-- ;
60
+ if ( this . #tail. length === 0 && this . #tail. next ) {
61
+ this . #tail = this . #tail. next ;
62
+ }
63
+ }
64
+ return item ;
65
+ }
66
+ }
67
+
68
+ module . exports = { UnrolledQueue } ;
Original file line number Diff line number Diff line change
1
+ 'use strict' ;
2
+
3
+ const { UnrolledQueue } = require ( './queue.js' ) ;
4
+
5
+ const mq = new UnrolledQueue ( { nodeSize : 8 } ) ;
6
+
7
+ for ( let id = 0 ; id < 5 ; id ++ ) {
8
+ mq . enqueue ( { id } ) ;
9
+ }
10
+
11
+ while ( mq . length ) {
12
+ const task = mq . dequeue ( ) ;
13
+ console . log ( `Processing ${ task . id } ` ) ;
14
+ }
15
+
16
+ for ( let id = 100 ; id < 105 ; id ++ ) {
17
+ mq . enqueue ( { id } ) ;
18
+ }
19
+
20
+ while ( mq . length ) {
21
+ const task = mq . dequeue ( ) ;
22
+ console . log ( `Processing ${ task . id } ` ) ;
23
+ }
You can’t perform that action at this time.
0 commit comments