Skip to content

Instantly share code, notes, and snippets.

@goodviber
Last active February 24, 2020 19:40
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 goodviber/ec931d6eb262bd39cf5eead945ee1ccb to your computer and use it in GitHub Desktop.
Save goodviber/ec931d6eb262bd39cf5eead945ee1ccb to your computer and use it in GitHub Desktop.
Theorem
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
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