Last active
September 6, 2016 18:05
-
-
Save vladCovaliov/8c924aec8d0717f1508f2a513f45123d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Ruby Version: 2.3.1p112 | |
# Author: Vlad Covaliov | |
# Date: 06.09.2016 | |
require 'test/unit' | |
module ArrayUtils | |
# Flatten nested array using a recursive method. Non-Destructive Method | |
# | |
# @param [Array, #read] content we want to flatten | |
# @return [Array] a new flat object with the contents | |
def recursive_flatten(object) | |
raise RuntimeError, "#{object.inspect} not convertible to array" unless object.respond_to?(:to_a) | |
result = [] | |
object.to_a.each do |elem| | |
if elem.kind_of?(Array) | |
result.push(*recursive_flatten(elem)) | |
else | |
result.push(elem) | |
end | |
end | |
result | |
end | |
end | |
class TestArrayUtils < Test::Unit::TestCase | |
include ArrayUtils | |
def test_recursive_flatten | |
# Negative test with wrong object type | |
assert_raise RuntimeError do | |
recursive_flatten("test") | |
end | |
# Negative test for nil | |
assert_equal([], recursive_flatten(nil)) | |
# Empty Array | |
assert_equal([], recursive_flatten([])) | |
# 1-level array | |
assert_equal([1,2,3], recursive_flatten([1,2,3])) | |
# 2-level array | |
assert_equal([1,2,3], recursive_flatten([[1],[2],[3]])) | |
# multi-level array | |
assert_equal([1,2,3,4,5,6], recursive_flatten([[1,2,[3]],[4,5],[[[6]]]])) | |
end | |
end | |
# Loaded suite ruby_flatten | |
# Started | |
# . | |
# Finished in 0.000457007 seconds. | |
# ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | |
# 1 tests, 6 assertions, 0 failures, 0 errors, 0 pendings, 0 omissions, 0 notifications | |
# 100% passed | |
# ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | |
# 2188.15 tests/s, 13128.90 assertions/s |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment