Created
February 7, 2017 10:29
-
-
Save Aerlinger/f94f178683f522224ed0c3ca21a7c8dd to your computer and use it in GitHub Desktop.
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
require "rspec" | |
def flatten(arr) | |
return [arr] unless arr.is_a? Array | |
arr.reduce([]) { |concat, item| concat + flatten(item) } | |
end | |
RSpec.describe "Flattening a nested array" do | |
it "is valid for simple array" do | |
expect(flatten([[1]])).to eq([1]) | |
end | |
it "is valid for empty array" do | |
expect(flatten([[]])).to eq([]) | |
end | |
it "is valid for partitioned array" do | |
expect(flatten([[1], [2], [3], [4], [5]])).to eq([1, 2, 3, 4, 5]) | |
end | |
it "is valid for array wrapped in array" do | |
expect(flatten([[1, 2, 3, 4, 5]])).to eq([1, 2, 3, 4, 5]) | |
end | |
it "is valid for deeply nested empty array" do | |
expect(flatten([[[], [], [], [nil]]])).to eq([nil]) | |
end | |
it "is valid for deeply nested inhomogeneous array" do | |
expect(flatten([[[], [{a: [1, [2]]}], ['a'], [nil]]])).to eq([{a: [1, [2]]}, 'a', nil]) | |
end | |
it "is valid for a flat array" do | |
expect(flatten([1, 2, 3, 4])).to eq([1, 2, 3, 4]) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment