Last active
March 1, 2018 19:40
-
-
Save alexagranov/dfa34a1b6700d459a0477759d14ff506 to your computer and use it in GitHub Desktop.
Flatten arbitrarily nested arrays without using #flatten :-)
This file contains hidden or 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
# frozen_string_literal: true | |
require 'test/unit' | |
class BespokeFlattenTest < Test::Unit::TestCase | |
def bespoke_flatten(arr, accum = []) | |
return arr unless arr.is_a?(Array) | |
until arr.empty? | |
elem = arr.shift | |
elem.is_a?(Array) ? bespoke_flatten(elem, accum) : (accum << elem) | |
end | |
accum | |
end | |
def test_non_array | |
a = 5 | |
assert_equal(5, bespoke_flatten(a)) | |
end | |
def test_single_element_array | |
a = [5] | |
assert_equal([5], bespoke_flatten(a)) | |
end | |
def test_multi_element_array | |
a = [5, 6] | |
assert_equal([5, 6], bespoke_flatten(a)) | |
end | |
def test_containing_one_nested_array | |
a = [3, [6]] | |
assert_equal([3, 6], bespoke_flatten(a)) | |
end | |
def test_containing_empty_arrays | |
a = [3, [], 6] | |
assert_equal([3, 6], bespoke_flatten(a)) | |
end | |
def test_containing_complex_nested_arrays | |
a = [3, [6, 9, [4, 5, [], 3, 2, [2, 4], 0], 3, 5], 23] | |
assert_equal([3, 6, 9, 4, 5, 3, 2, 2, 4, 0, 3, 5, 23], bespoke_flatten(a)) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment