Skip to content

Instantly share code, notes, and snippets.

@sebasjimenez10
Created November 14, 2017 23:53
Show Gist options
  • Save sebasjimenez10/6ed9184e9732817b4e5ca773981a7467 to your computer and use it in GitHub Desktop.
Save sebasjimenez10/6ed9184e9732817b4e5ca773981a7467 to your computer and use it in GitHub Desktop.
Array Flattener Implementation
# frozen_string_literal: true
# ArrayFlattener provides a method called `flatten_array` which returns a flat array
# from an array of nested arrays.
class ArrayFlattener
# The method uses a local variable
# as a memory object and passes it
# to the recursive method `recursive_flatten`
def flatten_array(arr)
result = []
recursive_flatten(arr, result)
result
end
private
# This method loops through the array
# and adds any element to the memory
# which isn't of Enumerable type and
# calls itself on elements which are Enumerable
def recursive_flatten(arr, memo)
if arr.is_a? Enumerable
arr.each do |element|
recursive_flatten(element, memo)
end
else
memo << arr
end
end
end
# frozen_string_literal: true
require 'minitest/autorun'
# Defines a test suite and acceptance criteria for the class ArrayFlattener
class TestArrayFlattener < Minitest::Test
def setup
@flattener = ArrayFlattener.new
end
def test_example_array
arr = [[1, 2, [3]], 4]
assert_equal [1, 2, 3, 4], @flattener.flatten_array(arr)
end
def test_3_level_deep
arr = [1, 2, [3, 4, [5], [6, 7]], 8]
assert_equal [1, 2, 3, 4, 5, 6, 7, 8], @flattener.flatten_array(arr)
end
def test_super_deep_array
arr = [[[[[[[[[[[[1, 2, 3, [4, [5], 6], 7]]]]]]]]]]]]
assert_equal [1, 2, 3, 4, 5, 6, 7], @flattener.flatten_array(arr)
end
def test_empty_array
arr = []
assert_equal [], @flattener.flatten_array(arr)
end
def test_single_number
arr = 1
assert_equal [1], @flattener.flatten_array(arr)
end
end
Run options: --seed 53704
# Running:
.....
Finished in 0.001275s, 3921.9470 runs/s, 3921.9470 assertions/s.
5 runs, 5 assertions, 0 failures, 0 errors, 0 skips
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment