dao-governance-framework/forum-network/public/classes/prioritized-queue.js

25 lines
584 B
JavaScript
Raw Normal View History

export class PrioritizedQueue {
constructor() {
this.buffer = [];
}
// Add an item to the buffer, ahead of the next lowest priority item
add(message, priority) {
const idx = this.buffer.findIndex((item) => item.priority < priority);
if (idx < 0) {
this.buffer.push({ message, priority });
} else {
this.buffer.splice(idx, 0, { message, priority });
}
}
// Return the highest priority item in the buffer
pop() {
if (!this.buffer.length) {
return null;
}
const item = this.buffer.shift();
return item.message;
}
}