Created
February 8, 2018 03:49
-
-
Save amuntasim/d7cf052933fccca956bfc816f39f69d5 to your computer and use it in GitHub Desktop.
Custom flatten implementation in ruby
This file contains 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
class FlattenTest | |
def self.custom_flatten(array, result = []) | |
array.each do |item| | |
if item.is_a? Array | |
custom_flatten(item, result) | |
else | |
result << item | |
end | |
end | |
result | |
end | |
end | |
RSpec.describe FlattenTest do | |
context '.custom_flatten' do | |
it 'should flatten array of arrays' do | |
expected = [1, 2, 3, 4, 5, 6] | |
expect(FlattenTest.custom_flatten([[1, 2], 3, [4, 5, 6]])).to eq expected | |
end | |
it 'should flatten nested array of arrays' do | |
expected = [1, 2, 3, 4, 5, 6, 7, 8, 9] | |
expect(FlattenTest.custom_flatten([[1, 2], 3, [4, 5, [6, [7, 8], 9]]])).to eq expected | |
end | |
it 'should return already flatten array' do | |
expected = [1, 2, 3, 4] | |
expect(FlattenTest.custom_flatten(expected)).to eq expected | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment