summaryrefslogtreecommitdiff
path: root/nodejs/lib/priority_queue.ts
blob: ec9e7d03332a87587c8a35f5dfdf655d98d59a50 (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
class QElement {
	element: unknown;
	priority: number;
	constructor(element: unknown, priority: number) {
		this.element = element;
		this.priority = priority;
	}
}

export class PriorityQueue {
	items: Array<QElement>;

	constructor(elt?: unknown) {
		this.items = [];
		if (elt !== undefined) this.enqueue(elt, 0);
	}

	enqueue(element: unknown, priority: number): void {
		let qElement = new QElement(element, priority);

		for (let i = 0; i < this.items.length; ++i) {
			if (this.items[i].priority > qElement.priority) {
				this.items.splice(i, 0, qElement);
				return;
			}
		}
		this.items.push(qElement);
	}
	dequeue(): unknown {
		// we would use pop to get the highest priority, shift() gives us the lowest priority
		return this.items.shift()?.element;
	}
	isEmpty(): boolean {
		return this.items.length === 0;
	}
}