5 ms·
I agree though one thing I would caution is it is good practice to always return the same type from a function even though it is an untyped language. The whole
by hokiewv 9y ago
I agree though one thing I would caution is it is good practice to always return the same type from a function even though it is an untyped language. The whole thing can be boiled down even more if pattern matching is used in parsing the initial string.
def convert(<<h::bytes-size(2)>> <> ":" <>
<<m::bytes-size(2)>> <> ":" <>
<<s::bytes-size(2)>> <> <<period::bytes-size(2)>>) do
"#{formatted_hour(h,period)}:#{m}:#{s}"
end
defp formatted_hour(hours,"PM"), do: "#{String.to_integer(hours) + 12}"
defp formatted_hour("12","AM"), do: "00"
defp formatted_hour(hours, "AM"), do: hours
- midgetjones 9y agoGood point! If you're going to pattern match in the initial string then who even needs the second function? def convert("12:" <> <<m::bytes-size(2)>> <> ":" <> <<s::bytes-size(2)>> <> "AM") do "00:#{m}:#{s}" end def convert(<<h::bytes-size(2)>> <> ":" <> <<m::bytes-size(2)>> <> ":" <> <<s::bytes-size(2)>> <> "PM") do h = 12 + String.to_integer(h) "#{h}:#{m}:#{s}" end def convert(<<h::bytes-size(2)>> <> ":" <> <<m::bytes-size(2)>> <> ":" <> <<s::bytes-size(2)>> <> "AM") do "#{h}:#{m}:#{s}" end Whether that's an improvement or not is another matter :)
- ericdouglas 9y agoCrazy stuff! :D I'm wondering how our future-self would feel about such cleverness haha
- ericdouglas 9y agoI really liked this: "#{String.to_integer(hours) + 12}" Used it now refactoring the code, many thanks for your suggestion!