Last active
September 1, 2015 16:01
-
-
Save ccarruitero/1c637bf0a9e79bb68a6f to your computer and use it in GitHub Desktop.
This file contains hidden or 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 'minitest/autorun' | |
module Flatten | |
def flatten_arr arr | |
return error_msg unless arr.is_a? Array | |
new_arr = [] | |
deep_flat(arr, new_arr) | |
end | |
def deep_flat arr, new_arr | |
arr.map do |item| | |
if item.is_a? Array | |
deep_flat(item, new_arr) | |
else | |
new_arr << item | |
end | |
end | |
new_arr | |
end | |
def error_msg | |
return 'Array is required' | |
end | |
end | |
class FlattenTest < Minitest::Test | |
include Flatten | |
def test_flatten_arr_with_no_array | |
assert_equal 'Array is required', flatten_arr(1) | |
end | |
def test_flatten_arr_with_array_like_item | |
arr = [1,2,[3],4] | |
assert_equal [1,2,3,4], flatten_arr(arr) | |
end | |
def test_flatten_arr_with_simple_array | |
arr = (1..4).to_a | |
assert_equal [1,2,3,4], flatten_arr(arr) | |
end | |
def test_flatten_arr_with_nested_array | |
arr = [[1,2,[3],4]] | |
flat_arr = flatten_arr arr | |
assert_equal [1, 2, 3, 4], flat_arr | |
end | |
def test_flatten_arr_with_more_nested_array | |
arr = [[1,2,[[3]],4]] | |
flat_arr = flatten_arr arr | |
assert_equal [1, 2, 3, 4], flat_arr | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment