-
Notifications
You must be signed in to change notification settings - Fork 9
/
Queue.js
66 lines (54 loc) · 1.35 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
/**
* @class Queue implement using Object
* FIFO (first in - first out)
*/
class Queue {
constructor(){
this.count = 0;
this.lowestCount = 0;
this.items = {};
}
equeue(element){
this.items[this.count] = element;
this.count ++;
}
/* remove the element which was insert first */
dequeue(){
if (this.isEmpty()) {
return undefined;
}
let result = this.items[this.lowestCount];
delete this.items[this.lowestCount];
this.lowestCount ++;
return result;
}
isEmpty(){
return this.count - this.lowestCount == 0;
}
size(){
return this.count - this.lowestCount;
}
peek(){
if (this.isEmpty()) {
return undefined;
}
return this.items[this.lowestCount];
}
clear(){
this.items = {}
this.count = 0;
this.lowestCount = 0;
return this.items;
}
toString(){
if (this.isEmpty()) {
return "";
}
let string = `${this.items[this.lowestCount]}`;
for (let index = this.lowestCount+1; index < this.count; index++) {
string = `${string},${this.items[index]}`;
}
return string;
}
}
module.exports = {Queue};