refactor day1 to use execute function
This commit is contained in:
parent
d84058d959
commit
3f047cd890
1 changed files with 15 additions and 9 deletions
24
lib/day1.ex
24
lib/day1.ex
|
@ -1,12 +1,4 @@
|
||||||
defmodule Day1 do
|
defmodule Day1 do
|
||||||
def to_command(s) do
|
|
||||||
try do
|
|
||||||
{:add, s |> String.trim() |> String.to_integer()}
|
|
||||||
rescue
|
|
||||||
ArgumentError -> {:reset}
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
def get_answer(state) do
|
def get_answer(state) do
|
||||||
elem(state, 1) |>
|
elem(state, 1) |>
|
||||||
Enum.reduce(0, fn i, acc -> i + acc end)
|
Enum.reduce(0, fn i, acc -> i + acc end)
|
||||||
|
@ -16,13 +8,27 @@ defmodule Day1 do
|
||||||
{nil, [0, 0, 0]}
|
{nil, [0, 0, 0]}
|
||||||
end
|
end
|
||||||
|
|
||||||
def apply_command(command, state) do
|
def execute(line, state) do
|
||||||
|
apply_command(
|
||||||
|
line |> to_command(),
|
||||||
|
state)
|
||||||
|
end
|
||||||
|
|
||||||
|
defp apply_command(command, state) do
|
||||||
case command do
|
case command do
|
||||||
{:add, n} -> apply_add(n, state)
|
{:add, n} -> apply_add(n, state)
|
||||||
{:reset} -> apply_reset(state)
|
{:reset} -> apply_reset(state)
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
defp to_command(s) do
|
||||||
|
try do
|
||||||
|
{:add, s |> String.trim() |> String.to_integer()}
|
||||||
|
rescue
|
||||||
|
ArgumentError -> {:reset}
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
defp apply_add(n, state) do
|
defp apply_add(n, state) do
|
||||||
{current, total} = state
|
{current, total} = state
|
||||||
new_current = n + if is_nil(current) do 0 else current end
|
new_current = n + if is_nil(current) do 0 else current end
|
||||||
|
|
Loading…
Add table
Reference in a new issue