@yaruno/priority-queue
Version:
Priority queue implementation in TypeScript
142 lines (137 loc) • 3.26 kB
JavaScript
// Priority Queue - A TypeScript implementation
// src/Node.ts
var Node = class {
constructor(value, priority) {
this.value = value;
this.priority = priority;
this.next = null;
this.prev = null;
}
setNext(next) {
this.next = next;
}
setPrev(prev) {
this.prev = prev;
}
getNext() {
return this.next;
}
getPrev() {
return this.prev;
}
getValue() {
return this.value;
}
getPriority() {
return this.priority;
}
};
// src/PriorityQueue.ts
var PriorityQueue = class {
constructor() {
this.head = null;
this.tail = null;
this.queueSize = 0;
}
//return queue size for now
enqueue(value, priority) {
const newNode = new Node(value, priority);
if (!this.head) {
this.head = newNode;
this.tail = newNode;
return this.queueSize++;
} else {
let pointer = this.head;
if (newNode.getPriority() > pointer.getPriority()) {
pointer.setPrev(newNode);
newNode.setNext(pointer);
this.head = newNode;
this.queueSize++;
} else {
while (pointer != null && pointer.getPriority() >= newNode.getPriority()) {
if (pointer.getNext() == null) {
pointer.setNext(newNode);
newNode.setPrev(pointer);
this.tail = newNode;
this.queueSize++;
break;
}
if (pointer.getPriority() == newNode.getPriority()) {
let temp = pointer;
let prev = pointer.getPrev();
prev == null ? void 0 : prev.setNext(newNode);
temp.setPrev(newNode);
newNode.setNext(temp);
newNode.setPrev(prev);
this.queueSize++;
break;
}
let next = pointer.getNext();
if (next != null) {
if (next.getPriority() < newNode.getPriority()) {
let temp = pointer;
temp.setNext(newNode);
next == null ? void 0 : next.setPrev(newNode);
newNode.setPrev(temp);
newNode.setNext(next);
this.queueSize++;
break;
}
}
pointer = pointer.getNext();
}
}
return this.queueSize;
}
}
peek() {
if (this.tail !== null) {
return {
value: this.tail.getValue(),
priority: this.tail.getPriority()
};
}
return null;
}
size() {
return this.queueSize;
}
dequeue() {
var _a;
let temp = null;
if (this.tail != null) {
temp = this.tail;
this.tail = this.tail.getPrev();
if ((_a = this.tail) == null ? void 0 : _a.getNext()) {
this.tail.setNext(null);
}
this.queueSize--;
return {
value: temp.getValue(),
priority: temp.getPriority()
};
}
return null;
}
clear() {
this.head = null;
this.tail = null;
this.queueSize = 0;
}
*[Symbol.iterator]() {
let current = this.tail;
while (current) {
yield {
value: current.getValue(),
priority: current.getPriority()
};
current = current.getPrev();
}
}
*drain() {
while (this.tail) {
yield this.dequeue();
}
}
};
export { PriorityQueue };