Skip to content

Instantly share code, notes, and snippets.

@sjain
Created September 27, 2019 04:11
Show Gist options
  • Save sjain/94b57cb05e3bbcfffcc0d7c5910e3392 to your computer and use it in GitHub Desktop.
Save sjain/94b57cb05e3bbcfffcc0d7c5910e3392 to your computer and use it in GitHub Desktop.
Array flattener
#!/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