How can we use built in priority queue in javascript
In chrome I am not able to run built in pq in javascript
JavaScript Task Queue Implementation: Prioritizing and Optimizing Code Execution
const taskQueue = [];
function enqueueTask(task, priority = 0) {
taskQueue.push({ task, priority });
taskQueue.sort((a, b) => a.priority - b.priority);
}
async function processQueue() {
while (taskQueue.length > 0) {
const { task, priority } = taskQueue.shift();
const startTime = performance.now();
await task();
const endTime = performance.now();
const executionTime = endTime - startTime;
console.log(`Task with priority ${priority} executed in ${executionTime.toFixed(2)} ms`);
}
}
function task1() {
return new Promise(resolve => {
setTimeout(() => {
console.log("Executing Task 1");
resolve();
}, 2000);
});
}
function task2() {
console.log("Executing Task 2");
}
function task3() {
return new Promise(resolve => {
setTimeout(() => {
console.log("Executing Task 3");
resolve();
}, 1500);
});
}
function task4() {
console.log("Executing Task 4");
}
enqueueTask(() => task1(), 2);
enqueueTask(() => task2(), 1);
enqueueTask(() => task3(), 3);
enqueueTask(() => task4(), 0);
processQueue();