Skip to content

Instantly share code, notes, and snippets.

@mrageh
Last active May 8, 2018 08:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrageh/16e9dd7ed3e1e91b49d51946a8a936f8 to your computer and use it in GitHub Desktop.
Save mrageh/16e9dd7ed3e1e91b49d51946a8a936f8 to your computer and use it in GitHub Desktop.
A custom implementation of Array#flatten
RSpec.describe "Custom implementation of Array Flatten" do
it 'flattens array containing empty array' do
list = [[]]
expect(custom_flatten(list)).to eq([])
end
it 'flattens array containing array with one element' do
list = [[1]]
expect(custom_flatten(list)).to eq([1])
end
it 'flattens array with two sub arrays' do
list = [[],[1,2,3,[4]]]
expect(custom_flatten(list)).to eq([1,2,3,4])
end
it 'flattens deeply nested array' do
list = [[[]],[[4,5,[1, [2,3,[4,5,6,[7,8,9]]]]]]]
expect(custom_flatten(list)).to eq([4,5,1,2,3,4,5,6,7,8,9])
end
end
def custom_flatten(list)
new_list = []
list.each do |element|
next if element.respond_to?(:empty?) && element.empty?
if element.is_a?(Array)
new_list += custom_flatten(element)
else
new_list << element
end
end
new_list
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment