Toposort
TypeScript toposort
Install / Use
/learn @n1ru4l/ToposortREADME
@n1ru4l/toposort
Why?
All toposort libraries I found where either JavaScript only, had a lot of dependencies, were cumbersome to deal with or did not produce dependency list that allowed detecting which tasks could be executed in parallel.
This library is basically a port of batching-toposort to TypeScript that uses modern ECMA structures such as Map and Set, as well as providing a utility toposortReverse function that I needed most of the time, when dealing with dependency lists.
This library also provides CommonJS and ES Module builds.
Install
yarn add -E @n1ru4l/toposort
Usage
toposort
Sort list of tasks.
import { toposort } from "@n1ru4l/toposort";
const tasks = new Map([
// after wakeUp is done we can do drinkCoffee and eatBreakfast
["wakeUp", ["drinkCoffee", "eatBreakfast"]],
["drinkCoffee", ["brushTeeth"]],
["eatBreakfast", ["brushTeeth"]],
["brushTeeth", ["floss"]],
// after flossing is done no further task must be done
["floss", []],
]);
const sorted = toposort(tasks);
console.log(sorted);
// [
// Set(1) { 'wakeUp' },
// Set(2) { 'drinkCoffee', 'eatBreakfast' },
// Set(1) { 'brushTeeth' },
// Set(1) { 'floss' }
// ]
toposortReverse
Most of the time I needed this instead of toposort. It is easier to grasp for my mind that task a depends on task b and c instead of declaring it the other way around. I am not sure about the naming. If you think a better naming is possible please send a pull request.
import { toposortReverse } from "@n1ru4l/toposort";
const graph = new Map([
// before we can drinkCoffee, we need to wakeUp
["drinkCoffee", ["wakeUp"]],
// before we can eatBreakfast, we need to wakeUp
["eatBreakfast", ["wakeUp"]],
// before we can brushTeeth, we need to drinkCoffee and eatBreakfast
["brushTeeth", ["drinkCoffee", "eatBreakfast"]],
// before we can floss, we need to brushTeeth
["floss", ["brushTeeth"]],
// wakeUp can be done without any dependencies
["wakeUp", []],
]);
const sorted = toposortReverse(graph);
// [
// Set(1) { 'wakeUp' },
// Set(2) { 'drinkCoffee', 'eatBreakfast' },
// Set(1) { 'brushTeeth' },
// Set(1) { 'floss' }
// ]
Related Skills
node-connect
345.4kDiagnose OpenClaw node connection and pairing failures for Android, iOS, and macOS companion apps
frontend-design
104.6kCreate distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.
openai-whisper-api
345.4kTranscribe audio via OpenAI Audio Transcriptions API (Whisper).
qqbot-media
345.4kQQBot 富媒体收发能力。使用 <qqmedia> 标签,系统根据文件扩展名自动识别类型(图片/语音/视频/文件)。
