Created
August 26, 2017 02:28
-
-
Save Ryan1729/c5047d07c3edc274b3e091674a45eba8 to your computer and use it in GitHub Desktop.
My own implementation of Array#flatten
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 characters
module Flatten | |
def flatten(array) | |
result = [] | |
array.each do |element| | |
if element.is_a? Array | |
flatten(element).each { |inner_element| result.push(inner_element) } | |
else | |
result.push(element) | |
end | |
end | |
result | |
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 characters
require 'minitest/autorun' | |
require_relative 'flatten' | |
class TestFlatten < Minitest::Test | |
include Flatten | |
def test_with_already_flat_array | |
array = [1, 2, 3, 4, 5] | |
assert_equal array, flatten(array) | |
end | |
def test_with_nested_array | |
array = [[1, 2, [3]], 4] | |
assert_equal [1, 2, 3, 4], flatten(array) | |
end | |
def test_random_array_has_expected_length | |
length = rand(16) | |
array = random_nested_array(length) | |
flattend = flatten(array) | |
message = "#{array} was flattened into #{flattend} which is not exactly #{length} elements long!" | |
assert_equal length, flattend.length, message | |
end | |
def test_random_array_is_flat | |
array = random_nested_array(rand(16)) | |
flattend = flatten(array) | |
is_flat = flattend.none? { |element| element.is_a? Array } | |
assert is_flat, "#{array} was flattened into #{flattend} which is not flat!" | |
end | |
def random_nested_array(length) | |
result = [] | |
current = result | |
(1..length).each do |i| | |
case rand(4) | |
when 1 | |
temp = [i] | |
current.push temp | |
current = temp | |
when 2 | |
current = result | |
current.push i | |
when 3 | |
current.push [i] | |
else | |
current.push i | |
end | |
end | |
result | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment