Skip to content

Instantly share code, notes, and snippets.

@aaroncadrian
Last active May 18, 2020 16:58
Show Gist options
  • Select an option

  • Save aaroncadrian/6484ea0ce0be7bfa14d38189bc2d4894 to your computer and use it in GitHub Desktop.

Select an option

Save aaroncadrian/6484ea0ce0be7bfa14d38189bc2d4894 to your computer and use it in GitHub Desktop.
Topological Sort implemented in TypeScript
import _ from 'lodash';
export function topSort(definitions: _.Dictionary<string[]>) {
const visited: _.Dictionary<boolean> = {};
const sorted: string[] = [];
const sortVertex = (vertex: string) => {
visited[vertex] = true;
for (const childVertex of _.get(definitions, vertex, <string[]>[])) {
if (visited[childVertex]) {
continue;
}
sortVertex(childVertex);
}
sorted.unshift(vertex);
};
for (const vertex of _.keys(definitions)) {
if (visited[vertex]) {
continue;
}
sortVertex(vertex);
}
return sorted;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment