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

43 lines
1.1 KiB
Ruby
Raw Normal View History

2018-08-13 11:25:01 +02:00
module Pruning
module Processing
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)
pruned_tree = @tree.dup
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
def prune_subtree(nodes, indicator_ids)
nodes_to_examine = nodes.dup
nodes_to_examine.each do |node|
if indicator_node?(node)
unwanted_indicator = !indicator_ids.include?(node['id'])
nodes.delete(node) if unwanted_indicator
else
has_no_wanted_indicators_in_children = prune_subtree(children(node), indicator_ids)
nodes.delete(node) if has_no_wanted_indicators_in_children
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) ||
node.fetch('categories', false) ||
node.fetch('indicators', false) ||
2018-08-13 11:25:01 +02:00
[]
end
def indicator_node?(node)
children(node).empty?
end
end
end
end