Skip to content

Commit

Permalink
Fix divide by zero error for averages on an empty collection (#14)
Browse files Browse the repository at this point in the history
  • Loading branch information
aharpervc authored Jun 26, 2020
1 parent fe22c8e commit 921c15f
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 0 deletions.
2 changes: 2 additions & 0 deletions lib/data-table/table.rb
Original file line number Diff line number Diff line change
Expand Up @@ -423,6 +423,8 @@ def calculate_sum(collection, column_name)
end

def calculate_avg(collection, column_name)
return 0 if collection.empty?

sum = calculate_sum(collection, column_name)
sum / collection.size
end
Expand Down
7 changes: 7 additions & 0 deletions spec/table_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,13 @@
expect(data_table.render).to \
eq(%{<table id='' class='data_table ' cellspacing='0' cellpadding='0'><caption></caption><thead><tr></tr></thead><tr><td class='empty_data_table' colspan='0'>#{text}</td></tr></table>})
end

it "avoids dividing by zero" do
data_table.column :power_level
data_table.total :power_level, :avg, 0
data_table.calculate_totals!
expect(data_table.total_calculations).to eq([{:power_level=>0}])
end
end

context 'with a more complicated setup' do
Expand Down

0 comments on commit 921c15f

Please sign in to comment.