Last active
May 18, 2020 16:58
-
-
Save aaroncadrian/6484ea0ce0be7bfa14d38189bc2d4894 to your computer and use it in GitHub Desktop.
Topological Sort implemented in TypeScript
This file contains hidden or 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
| 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