From ac79b5d4015306dc712520ce9de1863ff792780f Mon Sep 17 00:00:00 2001 From: Joshua Peek Date: Tue, 26 May 2009 20:37:57 -0500 Subject: [PATCH] add nesting height calculation --- lib/nested_multimap.rb | 27 +++++++++++++++++++++++++++ spec/nested_multimap_spec.rb | 21 +++++++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/lib/nested_multimap.rb b/lib/nested_multimap.rb index fd0a6fb..3f48ccd 100644 --- a/lib/nested_multimap.rb +++ b/lib/nested_multimap.rb @@ -47,6 +47,33 @@ def each_association end end + def each_container_with_default + each_container = Proc.new do |container| + if container.respond_to?(:each_container_with_default) + container.each_container_with_default do |value| + yield value + end + else + yield container + end + end + + hash_each_pair { |_, container| each_container.call(container) } + each_container.call(default) + + self + end + + def containers_with_default + containers = [] + each_container_with_default { |container| containers << container } + containers + end + + def height + containers_with_default.max { |a, b| a.length <=> b.length }.length + end + def inspect super.gsub(/\}$/, ", nil => #{default.inspect}}") end diff --git a/spec/nested_multimap_spec.rb b/spec/nested_multimap_spec.rb index eda2e38..c3d7b2c 100644 --- a/spec/nested_multimap_spec.rb +++ b/spec/nested_multimap_spec.rb @@ -105,6 +105,19 @@ ] end + it "should iterate over each container plus the default" do + a = [] + @map.each_container_with_default { |container| a << container } + a.should == [ + [100], + [200, 300], + [200], + [400, 500], + [500], + [] + ] + end + it "should iterate over each key" do a = [] @map.each_key { |key| a << key } @@ -131,6 +144,10 @@ @map.containers.should == [[100], [200, 300], [400, 500]] end + it "should list all containers plus the default" do + @map.containers_with_default.should == [[100], [200, 300], [200], [400, 500], [500], []] + end + it "should return array of keys" do @map.keys.should == ["a", ["b", "c"], ["b", "c"], ["c", "e"], ["c", "e"]] end @@ -138,6 +155,10 @@ it "should list all values" do @map.values.should == [100, 200, 300, 400, 500] end + + it "should return the distance to the deepest nesting level" do + @map.height.should == 2 + end end