Skip to content

Instantly share code, notes, and snippets.

@chukitow
Last active May 30, 2019 00:40
Show Gist options
  • Save chukitow/b5f13bef82a671d61b02e3e9d8d66dbc to your computer and use it in GitHub Desktop.
Save chukitow/b5f13bef82a671d61b02e3e9d8d66dbc to your computer and use it in GitHub Desktop.
Custom flatten method
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