Created
October 3, 2018 15:03
-
-
Save amiralles/cd7c6877365f262e0da404634530a537 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
def flatten array, res = Array.new | |
# 1. Does the candidate guard against invalid inputs? | |
return nil unless array | |
unless array.is_a?(Array) | |
# 2. When an error condition arises, does the candidate | |
# provides a comprehensive error message? | |
# (That is: an error message that other developer can | |
# look and immediately know what went wrong.) | |
# (*) See comments on die_arg_is_not_array for more details. | |
die_arg_is_not_array "array", array | |
end | |
# 3. This comment is interesting to me: | |
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | |
# As long as items concerns, there is no need to validate that | |
# they are of type integer because that doesn't change the | |
# way this method works. It can handle integers, strings, | |
# airplanes, whatever. | |
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | |
# In other words, it says: "I know that the spec states that | |
# this method is intended for ints, but since there is no harm | |
# in supporting other types of elements, let's do that instead | |
# of raising an error." | |
array.each do |e| | |
# 4. Does the candidate understand recursion? | |
if e&.is_a?(Array) | |
flatten(e).each { |se| res << se } | |
else | |
# 5. Another interesting comment: | |
# Plain element or nil. (In this context, nil is fine.) | |
# In other words: "nils are fine, that's why I don't | |
# null check on them". | |
res << e | |
end | |
end | |
return res | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment