Skip to content

Instantly share code, notes, and snippets.

@StasKoval
Forked from bronson/reports_controller.rb
Created December 31, 2015 20:34
Show Gist options
  • Save StasKoval/477f929e19678678b049 to your computer and use it in GitHub Desktop.
Save StasKoval/477f929e19678678b049 to your computer and use it in GitHub Desktop.
class ReportsController < ApplicationController
def group_columns columns, items
numitems = items.length
rows = numitems / columns
rows += 1 if numitems % columns > 0
extras = numitems % rows if rows > 0
1.upto(rows).map { |rownum|
# distribute the extras evenly
extra = 0
if extras > 0
extra = 1
extras -= 1
end
row = items.shift(numitems/rows + extra)
row + [nil] * (columns - row.length)
}
end
end
describe ReportsController do
let(:it) { described_class.new }
it "should group columns" do
def self.expect_this n, a
expect(it.group_columns(n, a.to_a))
end
n = nil
expect_this(3, [] ).to eq [ ]
expect_this(3, [1] ).to eq [[1, n, n] ]
expect_this(3, [1,2] ).to eq [[1, 2, n] ]
expect_this(3, [1,2,3] ).to eq [[1, 2, 3] ]
expect_this(3, [1,2,3,4] ).to eq [[1, 2, n], [3, 4, n] ]
expect_this(3, 1.upto(5) ).to eq [[1, 2, 3], [4, 5, n] ]
expect_this(3, 1.upto(6) ).to eq [[1, 2, 3], [4, 5, 6] ]
expect_this(3, 1.upto(7) ).to eq [[1, 2, 3], [4, 5, n], [6, 7, n]]
expect_this(3, 1.upto(8) ).to eq [[1, 2, 3], [4, 5, 6], [7, 8, n]]
expect_this(3, 1.upto(9) ).to eq [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
expect_this(4, [] ).to eq [ ]
expect_this(4, [1] ).to eq [[1, n, n, n] ]
expect_this(4, [1,2] ).to eq [[1, 2, n, n] ]
expect_this(4, [1,2,3] ).to eq [[1, 2, 3, n] ]
expect_this(4, [1,2,3,4] ).to eq [[1, 2, 3, 4] ]
expect_this(4, 1.upto(5) ).to eq [[1, 2, 3, n], [4, 5, n, n] ]
expect_this(4, 1.upto(6) ).to eq [[1, 2, 3, n], [4, 5, 6, n] ]
expect_this(4, 1.upto(7) ).to eq [[1, 2, 3, 4], [5, 6, 7, n] ]
expect_this(4, 1.upto(8) ).to eq [[1, 2, 3, 4], [5, 6, 7, 8] ]
expect_this(4, 1.upto(9) ).to eq [[1, 2, 3, n], [4, 5, 6, n], [7, 8, 9, n]]
expect_this(4, 1.upto(10) ).to eq [[1, 2, 3, 4], [5, 6, 7, n], [8, 9, 10, n]]
expect_this(4, 1.upto(11) ).to eq [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, n]]
expect_this(4, 1.upto(12) ).to eq [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment