Skip to content

Instantly share code, notes, and snippets.

@eanakashima
Created November 1, 2013 22:58
Show Gist options
  • Save eanakashima/7273298 to your computer and use it in GitHub Desktop.
Save eanakashima/7273298 to your computer and use it in GitHub Desktop.
Order an array so that elements can be floated across columns
# There is definitely an easier way to do this, but I'm spacing on what it is. >.<
# Takes an ordered list and re-orders it so elements can be css-floated and still appear in order.
# e.g. helper.column_order([1,2,3,4], 2) would produce [1,3,2,4] so elements appear on the page as |1 3|
# |2 4|
def column_order(list, number_of_columns)
remainder = list.length % number_of_columns
number_of_rows = list.length / number_of_columns + [remainder, 1].min
reordered_list = []
if remainder > 0
1.upto(number_of_columns - remainder - 1) { |i| list.insert(-i * number_of_columns, nil) } # pad the original array with nils
end
list.each_with_index do |item, index|
row = index % number_of_rows
reordered_list[row] ||= []
reordered_list[row] << item
end
reordered_list.flatten.compact
end
#====== SPECS
describe '#column_order' do
it 're-orders a list so it can be flowed horizontally but appear as vertical columns' do
# | 1 3 |
# | 2 4 |
expect(helper.column_order(['1','2','3','4'], 2)).to eq(['1','3','2','4'])
end
it 'also works with 3 columns' do
# | 1 3 5 |
# | 2 4 6 |
expect(helper.column_order(['1','2','3','4','5','6'], 3)).to eq(['1','3','5','2','4','6'])
end
it 'also works as a 3 x 3' do
# | 1 4 7 |
# | 2 5 8 |
# | 3 6 9 |
expect(helper.column_order(['1','2','3','4','5','6','7','8','9'], 3)).to eq(['1','4','7','2','5','8','3','6','9'])
end
it 'works with list lengths that do not divide into even columns (remainder 1)' do
# | 1 4 6 |
# | 2 5 7 |
# | 3 |
expect(helper.column_order(['1','2','3','4','5','6','7'], 3)).to eq(['1','4','6','2','5','7','3'])
end
it 'works with list lengths that do not divide into even columns (remainder 2)' do
# | 1 4 7 |
# | 2 5 8 |
# | 3 6 |
expect(helper.column_order(['1','2','3','4','5','6','7','8'], 3)).to eq(['1','4','7','2','5','8','3', '6'])
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment