Skip to content

Instantly share code, notes, and snippets.

@khelll
Last active September 10, 2019 13:25
Show Gist options
  • Save khelll/3144765bde05ac7daac3a173a28a382b to your computer and use it in GitHub Desktop.
Save khelll/3144765bde05ac7daac3a173a28a382b to your computer and use it in GitHub Desktop.
Ruby Implementation for `Array#flatten`, that flattens a map.
# rspec flatten.rb
def flatten(array)
return array if array == []
head, *tail = array
current = head.class == Array ? flatten(head) : [head]
current + flatten(tail)
end
RSpec.describe 'flatten' do
it 'returns [] for empty list' do
expect(flatten([])).to eq([])
end
it 'returns the same list if alreay flat' do
expect(flatten([1, 3, 5])).to eq([1, 3, 5])
end
it 'returns the flat list if the list is not flat' do
expect(flatten([1, [2, 3], [3, [4, 5]], [6, [7, [8]]], 9])).to eq([1, 2, 3, 3, 4, 5, 6, 7, 8, 9])
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment