-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqueue.js
57 lines (44 loc) · 1.05 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
// Queue
class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
class Queue {
constructor(value = "") {
this.first = null;
this.last = null;
if (value.toString().trim()) this.first = this.last = new Node(value);
}
enqueue(value = "") {
if (!value.toString().trim()) throw new Error("Invalid Value!");
const newNode = new Node(value);
if (!this.first) return (this.first = this.last = newNode);
// O(1)
this.last.next = newNode;
this.last = newNode;
}
dequeue() {
if (!this.first) throw new Error("Queue is Empty!");
if (this.first === this.last) return (this.first = this.last = null);
// O(1)
this.first = this.first.next;
}
toArray() {
let elements = [];
let currentNode = this.first;
// O(n)
while (currentNode) {
elements.push(currentNode.value);
currentNode = currentNode.next;
}
return elements;
}
get length() {
return this.toArray().length;
}
}
const queue = new Queue();
queue.enqueue(2);
console.log(queue);