Skip to content

Instantly share code, notes, and snippets.

@remigijusj
Created March 5, 2014 13:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save remigijusj/9367037 to your computer and use it in GitHub Desktop.
Save remigijusj/9367037 to your computer and use it in GitHub Desktop.
class Array
def deep_compact
term = []
hash = each_with_object({}) do |obj,res|
if obj.is_a?(Hash)
obj.each do |key,val|
res[key] ||= []
res[key] += val.respond_to?(:deep_compact) ? val.deep_compact : val
end
else
term << obj
end
end
hash.map {|it| Hash[*it] } + term
end
end
CASES = [
{
INPUT: [
{2=>[
{8=>[
{9=>[
{3=>[]}]}
]},
{8=>[
{7=>[]}
]}
]},
{1=>[
{5=>[
{7=>[]}
]},
{3=>[
{4=>[
{5=>[
{6=>[]}
]}
]}
]}
]}
],
OUTPUT: [
{2=>[
{8=>[
{9=>[
{3=>[]}
]},
{7=>[]}]}
]},
{1=>[
{5=>[
{7=>[]}
]},
{3=>[
{4=>[
{5=>[
{6=>[]}
]}
]}
]}
]}
]
},
{
INPUT: [
{1 => [:a], 2 => [:b]},
{1 => [:e], 3 => []},
{1 => [:f], 2 => [:g]},
{3 => [:x]}
],
OUTPUT: [
{1 => [:a, :e, :f]},
{2 => [:b, :g]},
{3 => [:x]},
]
},
]
CASES.each_with_index do |it,idx|
ok = it[:INPUT].deep_compact == it[:OUTPUT]
puts "#{idx}: #{ok ? :OK : :FAIL}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment