Created
September 27, 2019 04:11
-
-
Save sjain/94b57cb05e3bbcfffcc0d7c5910e3392 to your computer and use it in GitHub Desktop.
Array flattener
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
#!/usr/bin/env ruby | |
require 'minitest' | |
class ArrayFlattener | |
def perform(nested_array) | |
nested_array.inject([]) do |result, item| | |
if item.is_a?(Array) | |
result.push *self.perform(item) | |
else | |
result << item | |
end | |
end | |
end | |
end | |
class ArrayFlattenerTest < MiniTest::Test | |
def test_regular_array | |
flattener = ArrayFlattener.new | |
assert_equal [1,2,3,4], flattener.perform([1,2,3,4]) | |
end | |
def test_empty_array | |
flattener = ArrayFlattener.new | |
assert_equal [], flattener.perform([]) | |
end | |
def test_nested_array | |
flattener = ArrayFlattener.new | |
assert_equal [1,2,3,4], flattener.perform([1,2,[3],4]) | |
end | |
def test_deep_nested_array | |
flattener = ArrayFlattener.new | |
assert_equal [1,2,3,4], flattener.perform([1,[[2,[3]],4]]) | |
end | |
def test_ignore_empty_array | |
flattener = ArrayFlattener.new | |
assert_equal [1,3,4], flattener.perform([1,[],[3],4]) | |
end | |
end | |
MiniTest.run |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment