Created
June 25, 2016 07:48
-
-
Save taboularasa/4159b45b54c9a110d02e4dea2244227e to your computer and use it in GitHub Desktop.
flatten an Array
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
require 'minitest/autorun' | |
## | |
# Implement flatten | |
# | |
# ruby -Ilib:test flatten.rb | |
def flatten(accumulator, element) | |
if element.is_a? Array | |
element.each {|e| flatten(accumulator, e)} | |
else | |
accumulator << element | |
end | |
end | |
class TestFlatten < Minitest::Test | |
def test_handles_nested_array | |
input = [[1,2,[3]],4] | |
result = [] | |
expected = [1,2,3,4] | |
flatten(result, input) | |
assert_equal(result, expected) | |
end | |
def test_handles_flat_array | |
input = [1,2,3,4] | |
result = [] | |
expected = [1,2,3,4] | |
flatten(result, input) | |
assert_equal(result, expected) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment