@@ -29,33 +29,33 @@ topo_sort = function(nodes) {
2929 assert_data_table(nodes , ncols = 2L , types = c(" character" , " list" ))
3030 assert_names(names(nodes ), identical.to = c(" id" , " parents" ))
3131 assert_list(nodes $ parents , types = " character" )
32- assert_subset(unlist(nodes $ parents ), nodes $ id )
32+ assert_subset(unlist(nodes $ parents , use.names = FALSE ), nodes $ id )
3333 nodes = copy(nodes ) # copy ref to be sure
3434 n = nrow(nodes )
3535 # sort nodes with few parent to start
36- o = order(lengths(nodes $ parents ), decreasing = FALSE )
37- nodes = nodes [o ]
36+ nodes = nodes [order(lengths(parents ), decreasing = FALSE )]
3837
39- nodes $ topo = nodes $ depth = NA_integer_ # cols for topo-index and depth layer in sort
38+ nodes [, `:=`( topo = NA_integer_ , depth = NA_integer_ )] # cols for topo-index and depth layer in sort
4039 j = 1L
4140 topo_count = 1L
4241 depth_count = 0L
42+ topo = depth = parents = id = NULL
4343 while (topo_count < = n ) {
4444 # if element is not sorted and has no deps (anymore), we sort it in
4545 if (is.na(nodes $ topo [j ]) && length(nodes $ parents [[j ]]) == 0L ) {
46- nodes $ topo [ j ] = topo_count
46+ nodes [ j , topo : = topo_count ]
4747 topo_count = topo_count + 1L
48- nodes $ depth [ j ] = depth_count
48+ nodes [ j , depth : = depth_count ]
4949 }
5050 j = (j %% n ) + 1L # inc j, but wrap around end
51- if (j == 1 ) { # we wrapped, lets remove nodes of current layer from deps
52- layer = nodes [nodes $ depth == depth_count ] $ id
51+ if (j == 1L ) { # we wrapped, lets remove nodes of current layer from deps
52+ layer = nodes [.( depth_count ), id , on = " depth" , nomatch = NULL ]
5353 if (length(layer ) == 0L ) {
5454 stop(" Cycle detected, this is not a DAG!" )
5555 }
56- nodes $ parents = list ( map(nodes $ parents , function (x ) setdiff(x , layer )))
56+ nodes [, parents : = map(parents , function (x ) setdiff(x , layer ))]
5757 depth_count = depth_count + 1L
5858 }
5959 }
60- nodes [order(nodes $ topo ), c(" id" , " depth" )] # sort by topo, and then remove topo-col
60+ nodes [order(topo ), c(" id" , " depth" )] # sort by topo, and then remove topo-col
6161}
0 commit comments