File tree 1 file changed +11
-39
lines changed
1 file changed +11
-39
lines changed Original file line number Diff line number Diff line change 2
2
3
3
module . exports = class Queue {
4
4
constructor ( items ) {
5
- this . first = null ;
6
- this . last = null ;
7
- this . recycle = [ ] ;
8
- this . length = 0 ;
9
- if ( items ) {
10
- for ( const item of items ) {
11
- this . enqueue ( item ) ;
12
- }
13
- }
5
+ this . set = new Set ( items ) ;
6
+ this . iterator = this . set [ Symbol . iterator ] ( ) ;
7
+ }
8
+
9
+ get length ( ) {
10
+ return this . set . size ;
14
11
}
15
12
16
13
enqueue ( item ) {
17
- const first = this . first ;
18
- let node ;
19
- if ( this . recycle . length > 0 ) {
20
- node = this . recycle . pop ( ) ;
21
- node . item = item ;
22
- node . next = null ;
23
- } else {
24
- node = {
25
- item,
26
- next : null
27
- } ;
28
- }
29
- if ( first === null ) {
30
- this . last = node ;
31
- } else {
32
- first . next = node ;
33
- }
34
- this . first = node ;
35
- this . length ++ ;
14
+ this . set . add ( item ) ;
36
15
}
37
16
38
17
dequeue ( ) {
39
- const last = this . last ;
40
- if ( last === null )
41
- return undefined ;
42
- const next = last . next ;
43
- if ( next === null ) {
44
- this . first = null ;
45
- }
46
- this . last = next ;
47
- this . length -- ;
48
- this . recycle . push ( last ) ;
49
- return last . item ;
18
+ const result = this . iterator . next ( ) ;
19
+ if ( result . done ) return undefined ;
20
+ this . set . delete ( result . value ) ;
21
+ return result . value ;
50
22
}
51
23
} ;
You can’t perform that action at this time.
0 commit comments