Skip to content

Commit

Permalink
Cover rest of bag.
Browse files Browse the repository at this point in the history
  • Loading branch information
Brian Murphy-Dye committed Jul 16, 2015
1 parent 58d6b45 commit 6f261de
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
5 changes: 4 additions & 1 deletion lib/bag.rb
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,12 @@ def empty?
end

def as_sorted_counts
@bag.sort_by{ |key, cnt| cnt }
@bag.sort_by{ |key, cnt| -cnt }
end

private

# for cloning
def initialize_copy(source)
@bag = source.bag.clone
super
Expand Down
24 changes: 24 additions & 0 deletions spec/bag_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,39 @@
describe Bag do
subject(:bag) { Bag.new }

it 'handles empty bag' do
expect(bag).to be_empty
expect(bag.size).to eq(0)
expect(bag.count).to eq(0)
expect(bag.bag).to eq({})
expect(bag.as_sorted_counts).to eq([])
end

it 'handles repetitions' do
bag << 1 << 1 << 2 << 1 << 'a'
expect(bag.keys).to eq([1,2,'a'])
end

it 'clones well' do
bag << 1 << 1 << 2 << 1 << 'a'
new_bag = bag.clone
expect( bag.as_sorted_counts).to eq([[1,3],[2,1],['a',1]])
expect(new_bag.as_sorted_counts).to eq([[1,3],[2,1],['a',1]])
bag << 'a'
expect( bag.as_sorted_counts).to eq([[1,3],['a',2],[2,1]])
expect(new_bag.as_sorted_counts).to eq([[1,3],[2,1],['a',1]])
end

it 'handles #each' do
bag << 1 << 1 << 2 << 1 << 'a'
hash = {}
bag.each{ |key,val| hash[key] = val }
expect(bag.size).to eq(3)
expect(bag.count).to eq(5)
expect(hash).to eq({1=>3, 2=>1, 'a'=>1})
expect(bag[1]).to eq(3)
expect(bag['a']).to eq(1)
expect(bag.bag).to eq(hash)
expect(bag.as_sorted_counts).to eq([[1,3],[2,1],['a',1]])
end
end

0 comments on commit 6f261de

Please sign in to comment.