Skip to content

Instantly share code, notes, and snippets.

@Andrew-Max
Created March 22, 2017 03:06
Show Gist options
  • Save Andrew-Max/41a4a0ec94e489132bc771efdd14dbd7 to your computer and use it in GitHub Desktop.
Save Andrew-Max/41a4a0ec94e489132bc771efdd14dbd7 to your computer and use it in GitHub Desktop.
Array Flattener in Ruby for Citrusbyte
require 'test/unit'
extend Test::Unit::Assertions
class Flattener
# Public interface does input validation and delegates to private method
def flatten(input)
raise ArgumentError, 'Argument is not array' unless input.is_a? Array
recurse_flatten(input)
end
private
# No outside dependencies or side effects for simplicity
def recurse_flatten(arr)
accumulator = []
if arr.kind_of?(Array)
arr.each do |arr|
accumulator.concat(recurse_flatten(arr))
end
else
accumulator.concat([arr])
end
return accumulator
end
end
flattener = Flattener.new
single_level_array = [4, 8, 1]
four_level_array = [1, [2,3, [4, [3, 9, 3]]]]
multi_type_array = [[1,2,[3, ['a', 'b', 'c'], false]],4, 'x', {name: "andrew", age: 28}]
# Check that flattener doesn't hurt single level arrays.
assert_equal(flattener.flatten(single_level_array) , [4, 8, 1])
# Check that flattener can handle at least four levels of nesting
assert_equal(flattener.flatten(four_level_array) , [1, 2, 3, 4 ,3, 9, 3])
# Check that flattener can handle arrays of various classes
assert_equal(flattener.flatten(multi_type_array), [1, 2, 3, "a", "b", "c", false, 4, "x", {:name=>"andrew", :age=>28}])
# Check that flattener will not accept arguments for flatten other than arrays
assert_raise ArgumentError do
flattener.flatten(3)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment