Run Tasks Within a Time Budget

Write the code, see it run, pass the checks.

The problem

  • easy
  • Code

Write runWithinBudget(tasks, budgetMs, now). tasks is an array of functions that take no arguments and return a value or a promise of one, and now is a function that returns the current time in milliseconds: read the time only by calling now. Call now once at the start, then run the tasks one at a time, in order, waiting for each to finish before the next. Just before starting each task, check the time: once budgetMs or more have passed since the start, start no more tasks. A task that's already running is never interrupted, and its result counts even if it finishes past the budget. Return a promise of an object { results, skipped }: results holds the finished tasks' results in order, and skipped is how many tasks were never started. If a task's promise rejects, reject with its reason.

Your code must pass

  • Runs the tasks one at a time, in order
  • Starts no more tasks once the budget is used
  • Keeps the result of a task that finishes past the budget
  • Rejects with a failing task's reason
  • Resolves an empty array with nothing skipped