Added Topological Sort with Cycle Detection in Javascript #907
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Pull Request: Add Topological Sort with Cycle Detection (topoSort.js)
Changes Made
topoSort.js, a utility for topological sorting with explicit cycle detection.topoLevelsto group nodes by dependency levels using Kahn's algorithm.Implementation Summary
toGraph(input): normalizes input into an adjacency list and ensures all nodes are present.topoSort(input): DFS-based sort with a three-color state (unvisited/visiting/done). Detects cycles and throws an Error with a human-readable cycle path.topoLevels(input): Kahn’s algorithm variant that returns levels (sources first). Throws on cycles by delegating totopoSort.Usage Example
// Edges form: [from, to]
import { topoSort, topoLevels } from "./topoSort.js";
const edges = [["a","b"],["a","c"],["b","d"],["c","d"]];
const order = topoSort(edges); // ["a","b","c","d"] or ["a","c","b","d"]
const levels = topoLevels({ a:["b","c"], b:["d"], c:["d"], d:[] });
// levels = [["a"], ["b","c"], ["d"]]
Validation
Notes for Reviewers
This contribution is substantive and improves the repository’s algorithms coverage. Please add the label:
hacktoberfest-accepted
Thank you.