Last active
June 2, 2019 04:02
-
-
Save vedant1811/e2f7d981a2a13d70f547d26d60a9377f to your computer and use it in GitHub Desktop.
Flatten Array
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
def flatten_array(array) | |
ans = [] | |
array&.each do |element| | |
if element.is_a? Array | |
ans += flatten_array(element) | |
else | |
ans << element | |
end | |
end | |
ans | |
end |
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
# | |
# run tests using `rspec flatten_spec.rb` | |
require './flatten' | |
RSpec.describe "flatten" do | |
it do | |
input = [[1,2,[3]],4] | |
output = [1,2,3,4] | |
expect(flatten_array(input)).to eq(output) | |
end | |
it do | |
input = [[1,2,[]],4] | |
output = [1,2,4] | |
expect(flatten_array(input)).to eq(output) | |
end | |
it do | |
input = [[1,[[],[],[],[]],2,4]] | |
output = [1,2,4] | |
expect(flatten_array(input)).to eq(output) | |
end | |
it do | |
input = [] | |
output = [] | |
expect(flatten_array(input)).to eq(output) | |
end | |
it do | |
input = nil | |
output = [] | |
expect(flatten_array(input)).to eq(output) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment