Created
June 22, 2024 23:10
-
-
Save leonid-shevtsov/65f26c648b47a9a58a1ec13792245cb6 to your computer and use it in GitHub Desktop.
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
require 'json' | |
canvas = JSON.parse(STDIN.read, symbolize_names: true) | |
all_ids = canvas[:nodes].map { |n| n[:id] } | |
dest_ids = canvas[:edges].map {|e| e[:toNode] }.uniq | |
root_ids = all_ids - dest_ids | |
nodes_by_id = canvas[:nodes].to_h {|n| [n[:id],n] } | |
graph = canvas[:edges].group_by {|e| e[:fromNode] }.transform_values { |vv| vv.map {|v| v[:toNode] }} | |
tree = {} | |
walked_nodes = Set.new | |
root_ids.each do |root_id| | |
queue = [[root_id, tree]] | |
loop do | |
break if queue.empty? | |
node_id, tree_pointer = queue.shift | |
walked_nodes.add(node_id) | |
tree_pointer[node_id] = {} | |
neighbors = graph[node_id] | |
next if neighbors.nil? | |
neighbors.each do |neighbor_id| | |
unless walked_nodes.include?(neighbor_id) | |
queue.push([neighbor_id, tree_pointer[node_id]]) | |
end | |
end | |
end | |
end | |
def print_tree(nodes_by_id ,tree, indent) | |
tree.map do |node_id, children| | |
node = nodes_by_id[node_id] | |
spaces = ' '*indent | |
if node[:text] | |
puts node[:text].lines.map.with_index{|l,i| i==0 ? "#{spaces}- #{l}" : "#{spaces} #{l}"} | |
elsif node[:label] | |
puts "#{spaces}- #{node[:"label"]}" | |
elsif node[:file] | |
puts "#{spaces}- [[#{node[:file]}]]" | |
elsif node[:url] | |
puts "#{spaces}- #{node[:"url"]}" | |
else | |
puts "#{' '*indent}- #{node.to_json}" | |
end | |
print_tree(nodes_by_id, children, indent+1) | |
end | |
end | |
print_tree(nodes_by_id, tree, 0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment