Skip to content

Instantly share code, notes, and snippets.

@justinko
Last active July 29, 2019 19:12
Show Gist options
  • Save justinko/f1e0661ca16d572298c6769beef7aa8d to your computer and use it in GitHub Desktop.
Save justinko/f1e0661ca16d572298c6769beef7aa8d to your computer and use it in GitHub Desktop.
require 'rspec/autorun'
class FlattenArray
def self.call(array)
new(array).call
end
def initialize(array)
@array = array
@flat_array = []
end
def call(array = @array)
array.each do |element|
if element.is_a?(Array)
call(element)
else
@flat_array.push(element)
end
end
@flat_array
end
end
RSpec.describe FlattenArray do
describe '.call' do
def call(array)
FlattenArray.call(array)
end
context 'given an array with zero elements' do
it 'returns an empty array' do
expect(call([])).to eq([])
end
end
context 'given an array with no nested arrays' do
it 'returns the array as is' do
expect(call([1, 2, 3])).to eq([1, 2, 3])
end
end
context 'given an array with nested arrays' do
it 'returns a single array with all elements' do
expect(call([1, [2, [3]]])).to eq([1, 2, 3])
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment