Last active
September 10, 2019 13:25
-
-
Save khelll/3144765bde05ac7daac3a173a28a382b to your computer and use it in GitHub Desktop.
Ruby Implementation for `Array#flatten`, that flattens a map.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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