Last active
March 7, 2022 15:25
-
-
Save Phryxia/0d18832e5e0c18521c2d3edead16d93f to your computer and use it in GitHub Desktop.
DFS based topological sort implementation for TypeScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type Id = number | |
export interface Dependency { | |
id: Id | |
dependencies: Id[] | |
} | |
const PENDING = 1 | |
const WRITTEN = 2 | |
export function sort<T extends Dependency>(dependencies: T[], entries: Id[]): Id[] { | |
const dup: Record<Id, 1 | 2> = {} | |
const result: Id[] = [] | |
function traverse(node: Dependency): void { | |
if (dup[node.id] === PENDING) throw new Error('circular dependency detected') | |
dup[node.id] = PENDING | |
for (const dependentId of node.dependencies) { | |
if (dup[dependentId] !== WRITTEN) { | |
traverse(dependencies[dependentId]) | |
} | |
} | |
result.push(node.id) | |
dup[node.id] = WRITTEN | |
} | |
entries.forEach(id => traverse(dependencies[id])) | |
return result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment