Advanced Task Scheduler with Dependency Resolution
Build a task scheduler function that accepts a list of asynchronous tasks with dependencies and executes them in the correct order. The scheduler must support concurrency for independent tasks and return results in dependency-resolved order.
Challenge prompt
You are asked to implement an advanced task scheduler in JavaScript. Each task is represented by an object with an `id`, an async `run` function, and an array of `dependencies` representing task ids that must complete before this task runs. Your scheduler function receives an array of these task objects and should execute tasks while respecting dependencies. Tasks with no dependencies can run immediately. Tasks can run concurrently where dependencies allow. The scheduler must return a Promise that resolves to an array of results ordered by the completion of each task (not input order). Tasks that fail should reject the entire scheduler promise immediately with the error. Requirements: - Detect circular dependencies and reject with an error. - Maximize concurrency without violating dependencies. - Collect results in order of completion. Implement this scheduler function and demonstrate its usage with several tasks having varied dependencies and async durations.
Guidance
- • Create a graph structure to track dependencies and the number of unresolved dependent tasks for each node.
- • Use a queue or similar structure to manage tasks ready to run (those with zero unresolved dependencies).
- • Run tasks concurrently but delay starting a task until all its dependencies have completed.
- • Use Promises to handle async execution and collect results as tasks complete.
Hints
- • Topological sorting algorithms like Kahn's algorithm handle dependency resolution and cycle detection.
- • Use a Map to store task ids to task objects for quick lookup.
- • Use Promise.allSettled or similar methods carefully to collect results but stop on first failure.
Starter code
async function taskScheduler(tasks) {
// Your code here
}Expected output
An array of task results in the order tasks complete successfully, or a rejection error if a cycle is detected or any task fails.
Core concepts
Challenge a Friend
Send this duel to someone else and see if they can solve it.