Last active
February 24, 2020 19:40
-
-
Save goodviber/ec931d6eb262bd39cf5eead945ee1ccb to your computer and use it in GitHub Desktop.
Revisions
-
goodviber revised this gist
Feb 24, 2020 . 1 changed file with 2 additions and 1 deletion.There are no files selected for viewing
This file contains hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -1,7 +1,8 @@ class ArrayFlattener #recursive function def flatten_this(arr) raise ArgumentError, 'Argument is not an array' unless arr.is_a? Array arr.each_with_object([]) do | element, flat_array | flat_array.push *( element.is_a?(Array) ? flatten_this(element) : element ) end -
goodviber created this gist
Feb 24, 2020 .There are no files selected for viewing
This file contains hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,10 @@ class ArrayFlattener def flatten_this(arr) raise ArgumentError, 'Argument is not an array' unless arr.is_a? Array arr.each_with_object([]) do | element, flat_array | flat_array.push *( element.is_a?(Array) ? flatten_this(element) : element ) end end end This file contains hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,31 @@ require 'minitest/autorun' require_relative 'array_flattener' class ArrayFlattenerTest < Minitest::Unit::TestCase def setup @array_flattener = ArrayFlattener.new end def test_with_empty_array assert_equal [], @array_flattener.flatten_this([[]]) end def test_with_a_string assert_raises ArgumentError do @array_flattener.flatten_this("1,2,3,4") end end def test_with_nested_array assert_equal [1,2,3,4], @array_flattener.flatten_this([[1,2,[3]],4]) end def test_with_flat_array assert_equal [1,2,3,4], @array_flattener.flatten_this([1,2,3,4]) end def test_with_recurring_elements assert_equal [1,1,1,1,2,3,4], @array_flattener.flatten_this([[[1],[1]],1,[1],2,3,4]) end end