Skip to content

Commit baf359e

Browse files
committed
Refactor main module, add tests
1 parent 459c7d1 commit baf359e

File tree

2 files changed

+24
-19
lines changed

2 files changed

+24
-19
lines changed

lib/beat_time.ex

Lines changed: 12 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -13,42 +13,37 @@ defmodule BeatTime do
1313

1414
@doc """
1515
Returns the current .beat time.
16-
17-
## Examples
18-
19-
iex> BeatTime.now()
20-
%BeatTime{300}
2116
"""
2217
@spec now() :: BeatTime.t(integer)
2318
def now() do
24-
current =
25-
DateTime.utc_now()
26-
|> Dumballah.Convert.to_unix()
27-
|> Dumballah.Calculate.add_time(:hours, 1) # UTC+01
19+
DateTime.utc_now()
20+
|> Dumballah.Convert.to_unix()
21+
|> to_beats()
22+
end
2823

24+
@doc """
25+
Returns the .beat time representation of a given UNIX time.
26+
"""
27+
@spec to_beats(integer) :: BeatTime.t(integer)
28+
def to_beats(current) do
2929
beats =
3030
current
31+
|> Dumballah.Calculate.add_time(:hours, 1) # UTC+01
3132
|> calculate_seconds_since_midnight()
32-
|> seconds_to_beats()
33+
|> Kernel.*(1000)
34+
|> div(@beat)
3335

3436
%BeatTime{value: beats}
3537
end
3638

3739
@doc """
3840
Returns the text representation of a .beat time.
39-
40-
## Examples
41-
42-
iex> BeatTime.now() |> BeatTime.format()
43-
"@300"
4441
"""
4542
@spec format(BeatTime.t(integer)) :: String.t()
4643
def format(beat_time), do: "@#{beat_time.value}"
4744

4845
defp to_date_tuple(datetime), do: {datetime.year, datetime.month, datetime.day}
4946

50-
defp seconds_to_beats(seconds), do: (seconds * 1000) |> div(@beat)
51-
5247
defp calculate_seconds_since_midnight(unix_time) do
5348
day_start =
5449
unix_time

test/beat_time_test.exs

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,17 @@ defmodule BeatTimeTest do
22
use ExUnit.Case
33
doctest BeatTime
44

5-
test "greets the world" do
6-
assert BeatTime.hello() == :world
5+
test "returns time in beats" do
6+
unix_time = 1560794022
7+
expected_beats = 787
8+
9+
assert BeatTime.to_beats(unix_time) == %BeatTime{value: expected_beats}
10+
end
11+
12+
test "formats beat time" do
13+
beats = 787
14+
beat_time = %BeatTime{value: beats}
15+
16+
assert BeatTime.format(beat_time) == "@#{beats}"
717
end
818
end

0 commit comments

Comments
 (0)