Topological sort implementation in JavaScript