优先队列
function PriorityQueue() {
let items = [];
let activeElement = null;
// 队列元素
function QueueElement(element, priority) {
this.element = element;
this.priority = priority;
}
// 入列
this.enqueue = function (element, priority) {
const queueElement = new QueueElement(element, priority);
if (this.isEmpty()) {
items.push(queueElement);
// 第一个元素入列
setTimeout(() => {
this.showModal();
}, 0);
} else {
let added = false;
for (let i = 0; i < items.length; i++) {
// 判断重复弹窗入列
if (queueElement.priority === items[i].priority) {
added = true;
break;
}
// 根据优先度排序
if (queueElement.priority < items[i].priority) {
items.splice(i, 0, queueElement);
added = true;
break;
}
}
if (!added) {
items.push(queueElement);
}
}
};
// 出列
this.dequeue = function () {
if (!this.isEmpty()) {
if (activeElement) {
const { priority } = activeElement;
for (let i = 0; i < items.length; i++) {
if (priority == items[i].priority) {
items.splice(i, 1);
activeElement = null;
break;
}
}
} else {
items.shift();
}
}
};
this.dequeueByObject = function(priority) {
if(!this.isEmpty()){
for (let i = 0; i < items.length; i++) {
if (priority == items[i].priority) {
items.splice(i, 1);
break;
}
}
}
}
// 弹窗逻辑处理
this.showModal = function () {
if (!this.isEmpty()) {
activeElement = this.front();
activeElement.element.show();
}
};
// 队首
this.front = function () {
return items[0];
};
// 是否为空
this.isEmpty = function () {
return items.length === 0;
};
// 清空队列
this.clear = function () {
items = [];
};
// 队列长度
this.size = function () {
return items.length;
};
// 打印队列
this.print = function () {
for (let i = 0; i < items.length; i++) {
console.log(items[i]);
}
};
}
export default PriorityQueue;