Created
February 2, 2020 12:52
-
-
Save alco/ed213fc92510aa899984700c5c4fc04f 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
defmodule TimeFormat do | |
def format(seconds) do | |
hours = div(seconds, 3600) | |
remainder = rem(seconds, 3600) | |
minutes = div(remainder, 60) | |
seconds = rem(remainder, 60) | |
format(hours, minutes, seconds) | |
end | |
defp format(0, minutes, seconds), do: "#{minutes}:#{pad(seconds)}" | |
defp format(hours, minutes, seconds), do: "#{hours}:#{pad(minutes)}:#{pad(seconds)}" | |
defp pad(number), do: :io_lib.format('~2..0B', [number]) | |
end |
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
defmodule TimeFormatTest do | |
use ExUnit.Case | |
import TimeFormat | |
test "format/1 conforms to the spec" do | |
assert "0:00" == format(0) | |
assert "0:57" == format(57) | |
assert "0:59" == format(59) | |
assert "1:59" == format(119) | |
assert "22:01" == format(22 * 60 + 1) | |
assert "59:00" == format(59 * 60) | |
assert "59:09" == format(59 * 60 + 9) | |
assert "59:59" == format(59 * 60 + 59) | |
assert "1:00:00" == format(3600) | |
assert "1:00:01" == format(3601) | |
assert "1:01:00" == format(3660) | |
assert "1:01:01" == format(3661) | |
assert "1:12:21" == format(3600 + 12 * 60 + 21) | |
assert "2:12:21" == format(2 * 3600 + 12 * 60 + 21) | |
assert "12:12:21" == format(12 * 3600 + 12 * 60 + 21) | |
assert "0:07" == format(7) | |
assert "0:30" == format(30) | |
assert "1:00" == format(60) | |
assert "12:12" == format(12 * 60 + 12) | |
assert "1:23:04" == format(3600 + 23 * 60 + 4) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment