Topologically sort tasks by dependencies in deterministic order
Build tools, package managers, and CI pipelines all need to run tasks in an order that respects their dependencies. Implement orderTasks(tasks), which returns a valid run order.
orderTasks(tasks) // => string[]
tasks is an object whose keys are task names and whose values are arrays of the task names that must run before that task.
Object.keys(tasks). (Task names in tests are never integer-like, so key order is insertion order.)tasks, throw an Error whose message contains unknown and the missing name. Check this before anything else.Error whose message contains cycle.[]. Do not mutate tasks or its arrays.orderTasks({
deploy: ['test', 'build'],
build: ['install'],
lint: ['install'],
test: ['build'],
install: [],
});
// => ['install', 'build', 'lint', 'test', 'deploy']
// install is the only ready task. Then build and lint are ready: build is listed first.
// Then lint and test are ready: lint is listed first. Then test, then deploy.
orderTasks({ fonts: [], icons: [], styles: ['fonts'] });
// => ['fonts', 'icons', 'styles']
orderTasks({ fonts: [], styles: ['fonts'], icons: [] });
// => ['fonts', 'styles', 'icons']
// After fonts, styles becomes ready and is listed before icons.
orderTasks({ api: ['db'], db: ['cache'], cache: ['api'] });
// throws Error (cycle)
orderTasks({ app: ['router'] });
// throws Error (unknown dependency: router)