Last active
July 29, 2019 19:12
-
-
Save justinko/f1e0661ca16d572298c6769beef7aa8d 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/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