Skip to content

Commit

Permalink
add nesting height calculation
Browse files Browse the repository at this point in the history
  • Loading branch information
josh committed May 27, 2009
1 parent 240d66e commit ac79b5d
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
27 changes: 27 additions & 0 deletions lib/nested_multimap.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
21 changes: 21 additions & 0 deletions spec/nested_multimap_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
Expand All @@ -131,13 +144,21 @@
@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

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


Expand Down

0 comments on commit ac79b5d

Please sign in to comment.