From 92cadb76ed62d9bbc12f1296cb346e40e9d19655 Mon Sep 17 00:00:00 2001 From: Senad Uka Date: Mon, 13 Aug 2018 12:48:47 +0200 Subject: [PATCH] DFS is working --- lib/api/tree.rb | 4 ++++ lib/http/query.rb | 5 +++-- lib/pruner.rb | 34 ++++++++++++++++++++++------------ 3 files changed, 29 insertions(+), 14 deletions(-) diff --git a/lib/api/tree.rb b/lib/api/tree.rb index f22734c..1705d30 100644 --- a/lib/api/tree.rb +++ b/lib/api/tree.rb @@ -15,3 +15,7 @@ module Pruning end end end + + + + diff --git a/lib/http/query.rb b/lib/http/query.rb index 4519524..0197c73 100644 --- a/lib/http/query.rb +++ b/lib/http/query.rb @@ -2,11 +2,12 @@ module Pruning module HTTP class Query < Struct.new(:name, :indicator_ids) def initialize(params = {}) + symbolised = params.map { |k, v| { k.to_sym => v } }.reduce({}, :merge) values = members.map do |member| - value = params.fetch(member, nil) + value = symbolised.fetch(member, nil) next if value.nil? case member - when :indicator_ids then value.map(&:to_i) # break on purpose if indicator_ids is not an array + when :indicator_ids then value.map(&->(indicator_id) { indicator_id.to_i } ) # break on purpose if indicator_ids is not an array when :name then value.to_s.gsub(/[^A-Za-z]/,'') else value end diff --git a/lib/pruner.rb b/lib/pruner.rb index f7e19c0..5ad9a50 100644 --- a/lib/pruner.rb +++ b/lib/pruner.rb @@ -2,25 +2,35 @@ module Pruning module Processing class Pruner - def initialize(tree, indicator_ids) + def initialize(tree) @tree = tree end - def prune_tree(nodes, indicator_ids) - nodes.delete_if do |node| - unwanted_indicator = indicator_node?(node) && !indicator_ids.include?(node['id']) - has_no_wanted_indicators_in_children = prune_tree(children(node), indicator_ids) - - unwanted_indicator && has_no_wanted_indicators_in_children - end - nodes.empty? + def prune_tree(indicator_ids) + pruned_tree = @tree.dup + prune_subtree(pruned_tree, indicator_ids) + pruned_tree end 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 + nodes.empty? + end + def children(node) - node.get('sub-themes', false) || - node.get('categories', false) || - node.get('indicators', false) || + node.fetch('sub_themes', false) || + node.fetch('categories', false) || + node.fetch('indicators', false) || [] end