-
Notifications
You must be signed in to change notification settings - Fork 0
/
PriorityQueue.js
104 lines (88 loc) · 2.27 KB
/
PriorityQueue.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
const Node = require('./Node');
const defineProperty = Object.defineProperty;
/**
* Initializes a new instance of a PriorityQueue
* @constructs PriorityQueue
*/
function PriorityQueue() {
/**
* First Node in the PriorityQueue
* @name PriorityQueue#first
* @type {(Node|null)}
*/
this.first;
defineProperty(this, 'first', {
writable: true,
value: null /* default */
});
return this;
}
/**
* Checks if the priority queue is empty.
* @function PriorityQueue#isEmpty
*/
PriorityQueue.prototype.isEmpty = function () {
return this.first === null;
};
/**
* Adds a new item in order of its priority. The larger the number the higher the priority.
* @function PriorityQueue#enqueue
* @param {*} value Value to be enqueued
* @param {Number=} [priority = 0] Priority of the value
*/
PriorityQueue.prototype.enqueue = function (value, priority = 0) {
const newNode = new Node(value, priority);
if (this.isEmpty()) {
this.first = newNode;
} else {
if (newNode.priority > this.first.priority) {
newNode.setNext(this.first);
this.first = newNode;
} else {
let currentNode = this.first;
while (currentNode.hasNext()) {
if (newNode.priority > currentNode.getNext().priority) {
newNode.setNext(currentNode.getNext());
break;
}
currentNode = currentNode.getNext();
}
currentNode.setNext(newNode);
}
return this;
}
};
/**
* Removes and returns the first item in the queue.
* @function PriorityQueue#dequeue
*/
PriorityQueue.prototype.dequeue = function () {
if (this.isEmpty()) {
throw new Error('PriorityQueue is empty.');
} else {
const currentFirst = this.first;
this.first = currentFirst.getNext();
return currentFirst.value;
}
};
/**
* Returns the queue as string
* @function PriorityQueue#toString
*/
PriorityQueue.prototype.toString = function () {
if (this.isEmpty()) {
return '[Empty PriorityQueue]';
} else {
let queueAsString = '';
let currentNode = this.first;
while (currentNode) {
queueAsString += String(currentNode);
if (currentNode.hasNext()) {
queueAsString += ',';
}
currentNode = currentNode.getNext();
}
return queueAsString;
}
};
module.exports = PriorityQueue;