Skip to content

Instantly share code, notes, and snippets.

@vlad-velciov
Created May 17, 2019 09:13
Show Gist options
  • Save vlad-velciov/cef3dfbaf64e480ba0f4fb316efb303d to your computer and use it in GitHub Desktop.
Save vlad-velciov/cef3dfbaf64e480ba0f4fb316efb303d to your computer and use it in GitHub Desktop.
Recursively flatten an array
class FlattenableArray
def initialize(array)
@array = array
end
def flatten
flat = []
@array.each do |element|
if element.is_a? Array
flat.concat as_flattenable(element).flatten
else
flat << element
end
end
flat
end
private
def as_flattenable(element)
self.class.new element
end
end
describe FlattenableArray do
it 'raises an exception when a nil array is given' do
expect{FlattenableArray.new(nil)}.to raise_error 'You need to provide an array'
end
it 'returns an empty array when an empty array was given' do
subject = FlattenableArray.new([])
expect(subject.flatten).to eq([])
end
it 'returns the array if it has only one element' do
subject = FlattenableArray.new([1])
expect(subject.flatten).to eq([1])
end
it 'returns the array if it is already flat' do
subject = FlattenableArray.new([1, 2, 5,12])
expect(subject.flatten).to eq([1, 2, 5, 12])
end
it 'returns the first element if it is an array' do
subject = FlattenableArray.new([[1]])
expect(subject.flatten).to eq([1])
end
it 'returns the flattened array if two items are arrays with one element each' do
subject = FlattenableArray.new([[1], [2]])
expect(subject.flatten).to eq([1, 2])
end
it 'returns the flattened array if two items are arrays with more than one element each' do
subject = FlattenableArray.new([[1, 3, 5, 20], [2]])
expect(subject.flatten).to eq([1, 3, 5, 20, 2])
end
it 'returns the flattened array if an array is 3 levels deep' do
subject = FlattenableArray.new([[1, 3, [45, 89], 20], [2]])
expect(subject.flatten).to eq([1, 3, 45, 89, 20, 2])
end
it 'returns the flattened array if an array is 5 levels deep and has empty arrays within' do
subject = FlattenableArray.new([[1, 2, [3, 4], 5], [6], [7, [8, 9, [10, [11, 12, 13, []]]]]])
expect(subject.flatten).to eq([1,2,3,4,5,6,7,8,9,10,11,12,13])
end
it 'handles nil elements within the given array' do
subject = FlattenableArray.new([[1, 3, 5, 20, nil], [2, nil], nil])
expect(subject.flatten).to eq([1, 3, 5, 20, nil, 2, nil, nil])
end
it 'flattens the given example' do
subject = FlattenableArray.new( [[1,2,[3]],4])
expect(subject.flatten).to eq([1,2,3,4])
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment