Created
August 30, 2016 18:23
-
-
Save fastzen/39fbe69acbc1e154a68cd78a75929227 to your computer and use it in GitHub Desktop.
flatten
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 | |
# encoding: utf-8 | |
require "test/unit" | |
# Flatten an array given any nesting depth | |
def flatten(array, result = []) | |
return result unless array.is_a?(Array) | |
array.each do |element| | |
if element.is_a?(Array) | |
flatten(element, result) | |
else | |
result << element | |
end | |
end | |
return result | |
end | |
class TestFlatten < Test::Unit::TestCase | |
def test_flatten_no_array | |
source = 1 | |
target = [] | |
assert_equal( target, flatten( source ) ) | |
end | |
def test_flatten_no_depth | |
source = [1,2,3,4] | |
target = [1,2,3,4] | |
assert_equal( target, flatten( source ) ) | |
end | |
def test_flatten | |
source = [[1,2,[3]],4] | |
target = [1,2,3,4] | |
assert_equal( target, flatten( source ) ) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment