Skip to content

Instantly share code, notes, and snippets.

@stevenwanderski
Created October 30, 2016 22:37
Show Gist options
  • Save stevenwanderski/8da9febc2fbb558079a8abea4c517451 to your computer and use it in GitHub Desktop.
Save stevenwanderski/8da9febc2fbb558079a8abea4c517451 to your computer and use it in GitHub Desktop.
def flatten_array(input, base = [])
if !input.is_a?(Array)
raise 'When using `flatten_array`, an array must be supplied as the input.'
end
if !base.is_a?(Array)
raise 'When using `flatten_array`, an array must be supplied as the base.'
end
input.each do |element|
if element.is_a?(Array)
flatten_array(element, base)
else
base << element
end
end
base
end
describe 'flatten_array' do
context 'when input is an array' do
context 'and it contains nested arrays' do
it 'returns a flattened array' do
array = [[1, 2, [3]], 4]
new_array = flatten_array(array)
expect(new_array).to eq([1, 2, 3, 4])
end
end
context 'and it does not contain nested arrays' do
it 'returns a flattened array' do
array = [1, 2, 3, 4]
new_array = flatten_array(array)
expect(new_array).to eq([1, 2, 3, 4])
end
end
end
context 'when input is not an array' do
it 'raises an exception' do
expect {
flatten_array('BOOM!')
}.to raise_error('When using `flatten_array`, an array must be supplied as the input.')
end
end
context 'when base is not an array' do
it 'raises an exception' do
expect {
flatten_array([1], 'BOOM!')
}.to raise_error('When using `flatten_array`, an array must be supplied as the base.')
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment