Last active
February 24, 2020 19:40
-
-
Save goodviber/ec931d6eb262bd39cf5eead945ee1ccb to your computer and use it in GitHub Desktop.
Theorem
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
class ArrayFlattener | |
#recursive function | |
def flatten_this(arr) | |
raise ArgumentError, 'Argument is not an array' unless arr.is_a? Array | |
arr.each_with_object([]) do | element, flat_array | | |
flat_array.push *( element.is_a?(Array) ? flatten_this(element) : element ) | |
end | |
end | |
end |
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' | |
require_relative 'array_flattener' | |
class ArrayFlattenerTest < Minitest::Unit::TestCase | |
def setup | |
@array_flattener = ArrayFlattener.new | |
end | |
def test_with_empty_array | |
assert_equal [], @array_flattener.flatten_this([[]]) | |
end | |
def test_with_a_string | |
assert_raises ArgumentError do | |
@array_flattener.flatten_this("1,2,3,4") | |
end | |
end | |
def test_with_nested_array | |
assert_equal [1,2,3,4], @array_flattener.flatten_this([[1,2,[3]],4]) | |
end | |
def test_with_flat_array | |
assert_equal [1,2,3,4], @array_flattener.flatten_this([1,2,3,4]) | |
end | |
def test_with_recurring_elements | |
assert_equal [1,1,1,1,2,3,4], @array_flattener.flatten_this([[[1],[1]],1,[1],2,3,4]) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment