-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathqueue-linear.js
More file actions
44 lines (36 loc) · 815 Bytes
/
queue-linear.js
File metadata and controls
44 lines (36 loc) · 815 Bytes
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
export default class LinearQueue {
constructor() {
// membuat list, dikarenakan penggunaan method shift() kurang maksimal karena menghasilkan complexity O(n) - Linear. Maka kita bisa membuat list dengan object, key = 0 digunakan dalam hal ini.
this.items = {};
this.head = 0;
this.tail = 0;
}
enqueue(item) {
this.items[this.tail] = item;
this.tail++;
}
dequeue() {
if (this.isEmpty()) {
return null;
}
const item = this.items[this.head];
delete this.items[this.head];
this.head++;
return item;
}
peek() {
if (this.isEmpty()) {
return null;
}
return this.items[this.head];
}
isEmpty() {
return this.head === this.tail;
}
size() {
return this.tail - this.head;
}
print() {
return this.items;
}
}