aboutsummaryrefslogtreecommitdiff
path: root/2022/16-proboscidea-volcanium/priority_queue.js
blob: c1a5b6584b0a76d6bdcf8a357fb56f5ab25bb7b9 (plain)
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
export class QElement {
	constructor(element, priority) {
		this.element = element;
		this.priority = priority;
	}
}

export class PriorityQueue {
	constructor() {
		this.items = [];
	}

	enqueue(element, priority) {
		var qElement = new QElement(element, priority);
		var contain = false;

		for (var i = 0; i < this.items.length; i++) {
			if (this.items[i].priority > qElement.priority) {
				this.items.splice(i, 0, qElement);
				contain = true;
				break;
			}
		}
		if (!contain) {
			this.items.push(qElement);
		}
	}
	dequeue() {
		if (this.isEmpty()){
			throw "Attempting to dequeue an empty queue";
		}
		return this.items.shift();
	}
	front() {
		if (this.isEmpty()){
			throw "Attempting to front an empty queue";
		}
		return this.items[0];
	}
	rear() {
		if (this.isEmpty()){
			throw "Attempting to rear an empty queue";
		}
		return this.items[this.items.length - 1];
	}
	isEmpty() {
		return this.items.length == 0;
	}
	printPQueue() {
		var str = "";
		for (var i = 0; i < this.items.length; i++)
			str += this.items[i].element + " ";
		return str;
	}
}