Implement a `createScheduler()` with `add(task, priority)` and `run()`. Higher priority tasks run first.
Problem Statement
Implement a `createScheduler()` with `add(task, priority)` and `run()`. Higher priority tasks run first.
Complexity
Time Complexity: -
Space Complexity: -
Hints
š” Hint 1:
A priority queue processes items by priority, not insertion order.
š” Hint 2:
Sort tasks by priority (higher first) before running.
š” Hint 3:
Store tasks with priorities, sort on run(), and execute in order.
ā
Solution:
```javascript
function createScheduler() {
const tasks = [];
return {
add(task, priority) { tasks.push({ task, priority }); },
run() {
tasks.sort((a, b) => b.priority - a.priority);
return tasks.map(t => t.task());
}
};
}
```