Last active
July 21, 2017 09:02
-
-
Save apneadiving/09780094d8e80be10b3c8080a9ffe986 to your computer and use it in GitHub Desktop.
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
# test utility for the script | |
def assert(actual, expected) | |
if actual == expected | |
puts "ok #{expected}" | |
else | |
puts "ko, you expected: #{expected} but got #{actual}" | |
end | |
end | |
# first implementation, more functional programming friendly, pure method | |
def custom_flatten(arg) | |
if arg.respond_to?(:each) | |
arg.inject([]) {|ar, elt| ar + flatten(elt) } | |
else | |
[arg] | |
end | |
end | |
# benefit: only create one array, impure method though :) | |
def alternative_flatten(arg, result = []) | |
if arg.respond_to?(:each) | |
arg.each {|elt| flatten(elt, result) } | |
result | |
else | |
result.push arg | |
end | |
end | |
# tests | |
assert(custom_flatten(1), | |
[1]) | |
assert(custom_flatten([[1,2,[3]],4]), | |
[1,2,3,4]) | |
assert(custom_flatten([[ 1, 2, 3 ],[ 4, 5, 6, [7, 8] ], 9, 10]), | |
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) | |
# bonus | |
assert(custom_flatten([['a','b',['c']],'d']), | |
['a','b','c','d']) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment