Skip to content

Instantly share code, notes, and snippets.

@Mariusio
Created February 29, 2020 17:37
Show Gist options
  • Save Mariusio/fc5eacf1e336477d7eb3f7c584eebf15 to your computer and use it in GitHub Desktop.
Save Mariusio/fc5eacf1e336477d7eb3f7c584eebf15 to your computer and use it in GitHub Desktop.
class Array
# require and extend MiniTest for test_custom_flatten method
require 'test/unit/assertions'
extend Test::Unit::Assertions
# custom_flatten flattens an n-dimensional array and
# returns a single dimensional array.
#
# custom_flatten only works with arrays
# where each element is either an Integer or a
# (nested) Array.
#
# Examples:
# [-1,2,[-3],4].custom_flatten => [-1,2,-3,4]
# [[[[1,[2],[3]],4]]].custom_flatten => [1,2,3,4]
def custom_flatten(array = self, result = [])
array.each do |el|
if el.is_a? Array
# recursively call function if 'el' is a nested Array
custom_flatten(el, result)
elsif el.is_a? Integer
# 'el' is an Integer and is added to the result Array
result.push(el)
else
# raise ArgumentError because 'el' is not of type Array nor Integer
raise ArgumentError, 'Invalid params'
end
end
result
end
# test_custom_flatten tests the custom_flatten function of the Array class
def self.test_custom_flatten
# test that return value is an Array
assert_instance_of(Array, [1,2,3].custom_flatten)
# test that empty Array returns empty Array
assert_equal([], [].custom_flatten)
# test one-dimensional Array
assert_equal([1,2,3], [1,2,3].custom_flatten)
# test one-dimensional Array with nested empty Array
assert_equal([1,2,3], [1,[],2,3].custom_flatten)
# test two-dimensional Array
assert_equal([1,2,3,4], [1,2,[3],4].custom_flatten)
# test two-dimensional Array with negative integers
assert_equal([-1,2,-3,4], [-1,2,[-3],4].custom_flatten)
# test n-dimensional Array
assert_equal([1,2,3,4], [[[[1,[2],[3]],4]]].custom_flatten)
# test that ArgumentError is raised if Array contains
# something else than Integers or Arrays
assert_raise ArgumentError do
[1,2,3,'abc'].custom_flatten
end
assert_raise ArgumentError do
[1,2,3,4.5].custom_flatten
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment