Last active
May 30, 2019 00:40
-
-
Save chukitow/b5f13bef82a671d61b02e3e9d8d66dbc to your computer and use it in GitHub Desktop.
Custom flatten method
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
require 'minitest/autorun' | |
class FlattenArray | |
def self.for(collection) | |
new(collection).call | |
end | |
def initialize(collection) | |
@collection = collection | |
end | |
def call | |
flatten_array(@collection) | |
end | |
private | |
def flatten_array(collection, cache = []) | |
collection.each do |element| | |
if element.is_a?(Array) | |
flatten_array(element, cache) | |
else | |
cache << element | |
end | |
end | |
cache | |
end | |
end | |
class TestFlattenArray < Minitest::Test | |
def test_flatten_arry | |
assert_equal(FlattenArray.for([[1,2,[3]],4]), [1,2,3,4]) | |
end | |
def test_collection_is_not_mutated | |
collection = [[1,2,[3]],4] | |
FlattenArray.for(collection) | |
assert_equal(collection, [[1,2,[3]],4]) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment