Skip to content

Instantly share code, notes, and snippets.

@mikhailov
Last active Aug 29, 2015
Embed
What would you like to do?
flatten an array of arbitrarily nested arrays of integers into a flat array of integers (can't use Array#flatten built-in method)
class Flattenizer
def initialize(params)
if params.empty?
raise ArgumentError, 'Data set is empty'
end
if !params.is_a?(Array)
raise TypeError, 'Data set is not an array'
end
@input_array = params
end
def flatten
@resulted_array = []
inner_flatten_loop(@input_array)
return @resulted_array
end
private
def inner_flatten_loop(inner_array)
inner_array.each do |i|
if i.is_a?(Fixnum)
@resulted_array << i
elsif i.is_a?(Array)
inner_flatten_loop(i)
end
end
end
end
require 'minitest/autorun'
class TestFlattenizer < Minitest::Unit::TestCase
def test_that_array1_flattens
object = Flattenizer.new([[1,2,[3]],4]).flatten
assert_equal( [1,2,3,4], object )
end
def test_that_array2_flattens
object = Flattenizer.new([[1,2,[3],[[1]]],[1],[[[[3]]]],4]).flatten
assert_equal( [1,2,3,1,1,3,4], object )
end
def test_that_array3_flattens
object = Flattenizer.new([[1,2,[3]],"","bug",4]).flatten
assert_equal( [1,2,3,4], object )
end
def test_that_string_doesnt_flatten
assert_raises( TypeError ) { Flattenizer.new("string not an array") }
end
def test_that_empty_array_doesnt_flatten
assert_raises( ArgumentError ) { Flattenizer.new([]) }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment