Home
← All questions

Async Task Scheduler: DAG Dependencies and Concurrency Limit in JavaScript

HardPremiumJavaScript

Asked at Rippling · Uber · Amazon

JavaScript interview practice: Some jobs must wait for others to finish first. Start ready jobs together, but never run more workers than the allowed cap.

Problem

You are given a set of async jobs. Some jobs cannot start until other jobs have finished. Jobs with no remaining blockers may run at the same time, but you must never have more than limit jobs running at once.

Write a utility that accepts the job graph and the worker cap, runs every job exactly once under those rules, and resolves when the whole set is done.

function taskA(done){ console.log("Task A Completed"); done(); }
function taskB(done){ setTimeout(()=>{ console.log("Task B Completed"); done(); },2000); }
function taskC(done){ setTimeout(()=>{ console.log("Task C Completed"); done(); },200); }
function taskD(done){ console.log("Task D Completed"); done(); }
function taskE(done){ console.log("Task E Completed"); done(); }

const asyncGraph = {
  e: { dependency: ["c","d"], task: taskE },
  c: { task: taskC },
  d: { dependency: ["a","b"], task: taskD },
  a: { task: taskA },
  b: { task: taskB },
};

Example shape of the API you can implement:

function executeTasksInParallel(graph, limit) {
  // Your code here
}
Premium question

Unlock the in-browser editor, test cases, and model solution with Mentoxis Premium.

Unlock with Premium