Skip to content

Instantly share code, notes, and snippets.

@jasonyost
Last active July 22, 2016 02:13
Show Gist options
  • Save jasonyost/0c795771a270ebab6ce25f561f08b9cf to your computer and use it in GitHub Desktop.
Save jasonyost/0c795771a270ebab6ce25f561f08b9cf to your computer and use it in GitHub Desktop.
Flatten a nested array
module ArrFlatten
# Public: Returns a flat array
#
# nested_array - A nested array
#
# Examples
# nested_array = [ [1,2,3], [4,5,6], [7,8,9] ]
# ArrFlatten.arr_flatten(nested_array)
# => [1, 2, 3, 4, 5, 6, 7, 8, 9]
#
# Returns array
def self.arr_flatten(nested_array)
return [] unless nested_array.is_a?(Array)
nested_array.each_with_object([]) do |element, flattened|
flattened.push *(element.is_a?(Array) ? arr_flatten(element) : element)
end
end
end
require 'arr_flatten'
describe ArrFlatten do
let(:flat_array) { [1, 2, 3, 4, 5, 6, 7, 8, 9] }
let(:nested_example_1) { [ [1,2,3], [4,5,6], [7,8,9] ] }
let(:nested_example_2) { [ [1,2,3], 4,5,6, [7,8,9] ] }
let(:nested_example_3) { [ [1,2,3], 4,5,6, [7,[8,9]] ] }
describe '.arr_flatten(array)' do
context 'given no arguments' do
it 'should raise an ArgumentError' do
expect { subject.arr_flatten }.to raise_error ArgumentError
end
end
context 'given invalid arguments' do
context 'given a non-array' do
it 'should not raise an error' do
expect { subject.arr_flatten "not_an_array" }.not_to raise_error
end
it 'should return an empty array' do
a = subject.arr_flatten "not_an_array"
expect(a).to eq []
end
end
context 'given an empty array' do
it 'should return an empty array' do
a = subject.arr_flatten []
expect(a).to eq []
end
end
end
context 'given valid arguments' do
it 'should not throw an error' do
expect { ArrFlatten.arr_flatten flat_array }.not_to raise_error
end
context 'given a flat array' do
it 'should not alter the array' do
expect(subject.arr_flatten flat_array).to eq(flat_array)
end
end
context 'given an arbitrarily nested array' do
it 'should return an flat array' do
expect(subject.arr_flatten nested_example_1). to eq(flat_array)
expect(subject.arr_flatten nested_example_2). to eq(flat_array)
expect(subject.arr_flatten nested_example_3). to eq(flat_array)
end
end
end
end
end
⇒ rspec
ArrFlatten
.arr_flatten(array)
given no arguments
should raise an ArgumentError
given invalid arguments
given a non-array
should not raise an error
should return an empty array
given an empty array
should return an empty array
given valid arguments
should not throw an error
given a flat array
should not alter the array
given an arbitrarily nested array
should return an flat array
Finished in 0.00344 seconds (files took 0.09457 seconds to load)
7 examples, 0 failures
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment