-
Notifications
You must be signed in to change notification settings - Fork 164
/
Queue.js
118 lines (103 loc) · 2.36 KB
/
Queue.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
/**
* The Queue Class
* A queue is a first-in-first-out (FIFO) data structure -
* items are added to the end of the queue and removed from the front.
*/
export default class Queue {
/**
* The Queue Constructor
* @constructor
*/
constructor() {
this.head = null;
this.tail = null;
this.current = null;
this.length = 0;
}
/**
* Enqueues the given item
* @param {*} item
*/
enqueue(item) {
const node = {
data : item,
next : null
};
if (!this.head) {
this.head = node;
this.tail = node;
} else {
this.tail.next = node;
this.tail = node;
}
this.length += 1;
}
/**
* Dequeues and returns the first item in the Queue. If the Queue is empty it returns null.
* @returns {?*}
*/
dequeue() {
if (this.head) {
const aux = this.head;
this.head = this.head.next;
this.length -= 1;
return aux.data;
}
return null;
}
/**
* Returns the first element of the queue or null if the Queue is empty
* @returns {?*}
*/
get first() {
return this.head ? this.head.data : null;
}
/**
* Returns the last element of the queue or null if the Queue is empty
* @returns {?*}
*/
get last() {
return this.tail ? this.tail.data : null;
}
/**
* Returns the size of the queue
* @returns {Number}
*/
get size() {
return this.length;
}
/**
* Returns true if the queue is empty, and false otherwise
* @returns {Boolean}
*/
get isEmpty() {
return !this.head;
}
/**
* Starts the iterator at the head of the queue
*/
iterate() {
this.current = this.head;
}
/**
* Moves the iterator to the next element
*/
next() {
if (this.current) {
this.current = this.current.next;
}
}
/**
* Returns the current element of the Queue or null if there isn't one
*/
item() {
return this.current ? this.current.data : null;
}
/**
* Returns true if there are more elements after the current one
* @returns {Boolean}
*/
hasNext() {
return !!this.current;
}
}