Skip to content

Instantly share code, notes, and snippets.

@osazemeu
Last active June 20, 2019 20:05
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 osazemeu/341859ebc756856bc1390cc47dfe1c0a to your computer and use it in GitHub Desktop.
Save osazemeu/341859ebc756856bc1390cc47dfe1c0a to your computer and use it in GitHub Desktop.
This gist illustrates the flatten array method from ground up. :)
# This solution attempts to handle flattening of nested arrays gracefully
class CustomArray
def flatten(array)
raise 'input is not an array' unless array?(array)
return [] if array.empty?
recursive_flatten(array)
end
private
def array?(array_param)
array_param.is_a?(Array)
end
def recursive_flatten(array, results = [])
array.each do |element|
if array?(element)
recursive_flatten(element, results)
else
results << element
end
end
results
end
end
require 'minitest/autorun'
require_relative 'custom_array'
# Respective test to ensure correctness of code written
class CustomArrayTest < Minitest::Test
describe 'custom_array' do
def setup
@custom_array = CustomArray.new
end
it 'can get flatten response on expected inputs' do
expected_response = [1, 2, 3, 5, 6, 3, 6, 9, 7, 9, 0]
response = @custom_array.flatten([1, 2, 3, [5, 6, [3, 6, 9], 7, 9, 0]])
assert_equal expected_response, response
end
it 'raises an error on non-array inputs' do
assert_raises 'input is not an array' do
@custom_array.flatten('')
end
end
it 'returns empty arrays on empty array inputs' do
assert_equal [], @custom_array.flatten([])
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment