Skip to content

Instantly share code, notes, and snippets.

@kmckelvin
Created February 9, 2016 20:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kmckelvin/4e712a39126190ef5acc to your computer and use it in GitHub Desktop.
Save kmckelvin/4e712a39126190ef5acc to your computer and use it in GitHub Desktop.
Flattens arbitrarily nested arrays
class Flatten
def self.flatten(array)
array.reduce([]) do |acc, value|
if value.is_a?(Array)
acc += Flatten.flatten(value)
else
acc << value
end
end
end
end
require_relative 'flatten'
RSpec.describe Flatten do
describe ".flatten" do
context "when given an empty array as an input" do
it "returns an empty array" do
expect(Flatten.flatten([])).to eq []
end
end
context "when given a flat array as an input" do
it "returns the same array" do
initial = [1, 2, 3, 4]
expected = [1, 2, 3, 4]
expect(Flatten.flatten(initial)).to eq expected
end
end
context "when given a singly nested array" do
it "returns a new flattened array" do
initial = [1, [2], 3, 4]
expected = [1, 2, 3, 4]
result = Flatten.flatten(initial)
expect(result).to eq expected
end
it "does not modify the original array" do
initial = [1, [2], 3, 4]
result = Flatten.flatten(initial)
expect(initial).to eq [1, [2], 3, 4]
end
end
context "when given a deeply nested array" do
it "returns a new flattened array" do
initial = [1, [2, [3, 4, [5, 6, [7]], 8]], 9]
expected = [1, 2, 3, 4, 5, 6, 7, 8, 9]
result = Flatten.flatten(initial)
expect(result).to eq expected
end
end
end
end
source "https://rubygems.org"
gem 'rspec'
GEM
remote: https://rubygems.org/
specs:
diff-lcs (1.2.5)
rspec (3.4.0)
rspec-core (~> 3.4.0)
rspec-expectations (~> 3.4.0)
rspec-mocks (~> 3.4.0)
rspec-core (3.4.2)
rspec-support (~> 3.4.0)
rspec-expectations (3.4.0)
diff-lcs (>= 1.2.0, < 2.0)
rspec-support (~> 3.4.0)
rspec-mocks (3.4.1)
diff-lcs (>= 1.2.0, < 2.0)
rspec-support (~> 3.4.0)
rspec-support (3.4.1)
PLATFORMS
ruby
DEPENDENCIES
rspec
BUNDLED WITH
1.10.6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment