Files
old-pruning-excersise/lib/pruner.rb

47 lines
1.2 KiB
Ruby
Raw Normal View History

2018-08-13 11:25:01 +02:00
module Pruning
module Processing
2018-08-13 18:54:12 +02:00
# Contains methods that store the tree and prune everything
# except the branches with requested indicator
2018-08-13 11:25:01 +02:00
class Pruner
2018-08-13 12:48:47 +02:00
def initialize(tree)
2018-08-13 11:25:01 +02:00
@tree = tree
end
2018-08-13 12:48:47 +02:00
def prune_tree(indicator_ids)
2018-08-13 18:54:12 +02:00
pruned_tree = @tree
2018-08-13 12:48:47 +02:00
prune_subtree(pruned_tree, indicator_ids)
pruned_tree
end
2018-08-13 11:25:01 +02:00
2018-08-13 12:48:47 +02:00
private
2018-08-13 18:54:12 +02:00
2018-08-13 19:06:00 +02:00
# Depth First Search implementation
# With pruning on the same sweep
2018-08-13 12:48:47 +02:00
def prune_subtree(nodes, indicator_ids)
nodes_to_examine = nodes.dup
nodes_to_examine.each do |node|
2018-08-13 18:54:12 +02:00
if indicator_node?(node)
indicator_not_wanted = !indicator_ids.include?(node['id'])
nodes.delete(node) if indicator_not_wanted
else
no_wanted_children = prune_subtree(children(node), indicator_ids)
nodes.delete(node) if no_wanted_children
2018-08-13 12:48:47 +02:00
end
end
2018-08-13 11:25:01 +02:00
nodes.empty?
end
def children(node)
2018-08-13 12:48:47 +02:00
node.fetch('sub_themes', false) ||
2018-08-13 18:54:12 +02:00
node.fetch('categories', false) ||
node.fetch('indicators', false) ||
[]
2018-08-13 11:25:01 +02:00
end
2018-08-13 18:54:12 +02:00
2018-08-13 11:25:01 +02:00
def indicator_node?(node)
children(node).empty?
end
end
end
end