Skip to content

Instantly share code, notes, and snippets.

@adammbalogh
Created July 23, 2016 21:15
Show Gist options
  • Save adammbalogh/953323c44be9ffe3af0f88d9e0958256 to your computer and use it in GitHub Desktop.
Save adammbalogh/953323c44be9ffe3af0f88d9e0958256 to your computer and use it in GitHub Desktop.
# business logic file
module DataStructure
class Array
def initialize(array)
@array = array
end
def flatten
_flatten @array
end
def flatten!
@array = _flatten @array
end
def to_s
@array.to_s
end
def inspect
@array.inspect
end
private
def _flatten(array, flatten_array = [])
array.each do |element|
if element.kind_of?(::Array)
_flatten element, flatten_array
else
flatten_array.push element
end
end
flatten_array
end
end
end
# test file
require 'test/unit'
module DataStructure
class ArrayTest < Test::Unit::TestCase
def test_should_flat_the_input_array
data_provider.each do |test_data|
assert_equal (DataStructure::Array.new(test_data[:input])).flatten, test_data[:output]
end
end
def data_provider
[
{
input: [],
output: []
},
{
input: [1,2,3],
output: [1,2,3]
},
{
input: [1,[2,3]],
output: [1,2,3]
},
{
input: [[1,2,[3]],4],
output: [1,2,3,4]
},
{
input: [[1,2,[3,[4,5,6]]],7],
output: [1,2,3,4,5,6,7]
}
]
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment