Created
July 15, 2016 22:19
-
-
Save danascheider/4eb2ccf16f0113571a6c3d1254f74877 to your computer and use it in GitHub Desktop.
Function to flatten an array
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
--format documentation | |
--color | |
--require spec_helper |
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 Flatten | |
def flatten(array) | |
array.each_with_index do |item, index| | |
array.insert(index, *array.delete(item)) | |
end | |
end | |
end |
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
RSpec.describe Flatten do | |
describe "#flatten" do | |
context "array is already flat" do | |
let(:arr) { [ 1 ] } | |
it "returns the array unchanged" do | |
expect(subject.flatten(arr)).to eq arr | |
end | |
end | |
context "array with sub-array" do | |
let(:arr) { [ [ 1 ] ] } | |
it "returns the array flattened" do | |
expect(subject.flatten(arr)).to eq arr.flatten | |
end | |
end | |
context "longer array with sub-array" do | |
let(:arr) { [ 1, [ 2 ], 3, 4 ] } | |
it "returns the array flattened" do | |
expect(subject.flatten(arr)).to eq arr.flatten | |
end | |
end | |
context "multiple items in sub-array" do | |
let(:arr) { [ 1, [ 2, 3 ], 4 ] } | |
it "returns the array flattened" do | |
expect(subject.flatten(arr)).to eq arr.flatten | |
end | |
end | |
context "nested sub-arrays" do | |
let(:arr) { [ 1, [ 2, [ 3 ] ], 4 ] } | |
it "returns the array flattened" do | |
expect(subject.flatten(arr)).to eq arr.flatten | |
end | |
end | |
end | |
end |
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_relative "../flatten" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment