Last active
April 20, 2017 01:32
-
-
Save sheharyarn/f7e0972b222dc0bd1df1c2ced46521bc to your computer and use it in GitHub Desktop.
Ruby 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
class Array | |
## Returns a new flattened array | |
def custom_flatten | |
new_array = [] | |
# Recursively iterate over sub-arrays and other | |
# elements and concat them to the new array | |
self.each do |obj| | |
if obj.is_a?(Array) | |
new_array.concat(obj.custom_flatten) | |
else | |
new_array.push(obj) | |
end | |
end | |
return new_array | |
end | |
## Mutator method that flattens and updates | |
## an existing array | |
def custom_flatten! | |
self.replace(custom_flatten) | |
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
#!/usr/bin/env ruby | |
require 'test/unit' | |
require './flatten' | |
class TestFlatten < Test::Unit::TestCase | |
def test_if_the_flatten_methods_exist | |
array_methods = Array.new.methods | |
assert array_methods.member?(:custom_flatten) | |
assert array_methods.member?(:custom_flatten!) | |
end | |
def test_that_it_flattens_arrays_correctly | |
test_cases = [ | |
[], | |
[1], | |
[nil], | |
[1,[]], | |
[1,2,3], | |
[1,2,[3,4]], | |
[[1,2,[3]],4], | |
[1,2,[3,[4,5],6]], | |
[1,2,3,[4,[5,[]],[6]]], | |
[1,[2,[3,[4,[5,[6,[7]]]]]]] | |
] | |
test_cases.each do |arr| | |
assert_equal(arr.flatten, arr.custom_flatten) | |
end | |
end | |
def test_that_custom_flatten_does_not_change_the_original_array | |
array = [1, 2, 3, [4, 5]] | |
array.custom_flatten | |
assert_equal(array, [1, 2, 3, [4, 5]]) | |
end | |
def test_that_custom_flatten_bang_updates_the_original_array | |
array = [1, 2, 3, [4, 5]] | |
array.custom_flatten! | |
assert_equal(array, [1, 2, 3, 4, 5]) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment