Skip to content

Instantly share code, notes, and snippets.

@danascheider
Created July 15, 2016 22:19
Show Gist options
  • Save danascheider/4eb2ccf16f0113571a6c3d1254f74877 to your computer and use it in GitHub Desktop.
Save danascheider/4eb2ccf16f0113571a6c3d1254f74877 to your computer and use it in GitHub Desktop.
Function to flatten an array
--format documentation
--color
--require spec_helper
class Flatten
def flatten(array)
array.each_with_index do |item, index|
array.insert(index, *array.delete(item))
end
end
end
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
require_relative "../flatten"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment