Skip to content

Instantly share code, notes, and snippets.

@alexagranov
Last active March 1, 2018 19:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexagranov/dfa34a1b6700d459a0477759d14ff506 to your computer and use it in GitHub Desktop.
Save alexagranov/dfa34a1b6700d459a0477759d14ff506 to your computer and use it in GitHub Desktop.
Flatten arbitrarily nested arrays without using #flatten :-)
# 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