Skip to content

Instantly share code, notes, and snippets.

@leonid-shevtsov
Created June 22, 2024 23:10
Show Gist options
  • Save leonid-shevtsov/65f26c648b47a9a58a1ec13792245cb6 to your computer and use it in GitHub Desktop.
Save leonid-shevtsov/65f26c648b47a9a58a1ec13792245cb6 to your computer and use it in GitHub Desktop.
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