Hi guys, today I was giving exam for one company, it was on imocha, JS round in they asked a question on Asynchronous Priority Task Scheduler (async/await), I tried my 2/3 approach but that doesn't work, for your reference I am attaching the question and my approach, it would be very helpful if someone help me on that to know where I was wrong in my approach
#Asynchronous Priority Task Scheduler
7 messages · Page 1 of 1 (latest)
@somber igloo Looking at the code you shared, it seems the problem stems from await task.taskFunction(). Could you explain why you're using it there?
This line executes the asynchronous function (taskFunction) associated with the current task, and waits for it to complete before proceeding to the next task.
what's not working? what's the output of this code anyway?
It worked, this is the working code
class PriorityTaskScheduler {
constructor() {
this.tasks = [];
}
addTask(taskFunction, delay, priority) {
this.tasks.push({ taskFunction, delay, priority });
}
async executeTasks() {
this.tasks.sort((a, b) => {
if (a.priority !== b.priority) {
return a.priority - b.priority;
} else {
return a.delay - b.delay;
}
});
for (const task of this.tasks) {
await new Promise((resolve) => setTimeout(resolve, task.delay));
await task.taskFunction();
}
this.tasks = [];
}
}
// Main handler
(async () => {
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
terminal: false,
});
const scheduler = new PriorityTaskScheduler();
let inputLines = [];
let lineCount = 0;
let numCommands = 0;
rl.on('line', async (line) => {
if (lineCount === 0) {
numCommands = parseInt(line);
} else {
inputLines.push(line);
}
lineCount++;
if (inputLines.length === numCommands) {
for (let cmd of inputLines) {
if (cmd.startsWith('addTask')) {
let [, delayStr, priorityStr] = cmd.split(' ');
let delay = parseInt(delayStr);
let priority = parseInt(priorityStr);
const task = async () => {
console.log(`${delay} ${priority}`);
};
scheduler.addTask(task, delay, priority);
} else if (cmd === 'executeTasks') {
await scheduler.executeTasks();
}
}
rl.close();
}
});
})();