Last active
May 8, 2018 08:39
-
-
Save mrageh/16e9dd7ed3e1e91b49d51946a8a936f8 to your computer and use it in GitHub Desktop.
A custom implementation of Array#flatten
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.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