This solution is generated by ChatGPT, correctness is not guaranteed. You might also be able to find a solution fromcommunity posts.
AI solution for JavaScript Coding Question on BFE.dev
179. Implement AsyncTaskQueue
To implement the AsyncTaskQueue class, we need to consider the following steps:
- Initialize the queue with the specified concurrency limit:
- In the constructor, we can initialize an array to store the tasks and a variable to keep track of the number of tasks currently running.
- We also need to store the maximum concurrency limit specified when creating an instance of the
AsyncTaskQueue.
- Add an async task to the queue:
- In the
queuemethod, we need to add the task to the array of tasks and check if we can start the task immediately based on the concurrency limit. - If the number of running tasks is less than the concurrency limit, we can start the task by calling it and handling the Promise resolve and reject.
Here is the implementation of the AsyncTaskQueue class:
class AsyncTaskQueue { constructor(concurrency) { this.tasks = []; this.runningCount = 0; this.concurrency = concurrency; } async runTask(task) { try { await task(); } catch (error) { // Silently ignore the rejection } finally { this.runningCount--; this.runNextTask(); } } runNextTask() { if (this.runningCount < this.concurrency && this.tasks.length > 0) { const task = this.tasks.shift(); this.runningCount++; this.runTask(task); } } queue(task) { this.tasks.push(task); this.runNextTask(); }}
In the above code:
- The
runTaskmethod handles running each task and catches any error if the Promise rejects. - The
runNextTaskmethod is responsible for checking if there are more tasks to run and starting them based on the concurrency limit. - The
queuemethod adds the task to the array and starts the task if possible.
In the example usage provided:
- We create an instance of
AsyncTaskQueuewith a concurrency limit of 2. - Define three async tasks using Promises.
- Queue the tasks one after the other and observe the order of execution as per the concurrency limit specified.
This implementation ensures that tasks are executed in the order they are added to the queue while respecting the concurrency limit and handling Promise rejections gracefully.