From 3f047cd8905be76bd4846a1443d25ba87683f556 Mon Sep 17 00:00:00 2001 From: Caleb Webber Date: Sat, 28 Oct 2023 12:30:04 -0400 Subject: [PATCH] refactor day1 to use execute function --- lib/day1.ex | 24 +++++++++++++++--------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/lib/day1.ex b/lib/day1.ex index aeae8a8..effcde2 100644 --- a/lib/day1.ex +++ b/lib/day1.ex @@ -1,12 +1,4 @@ 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 elem(state, 1) |> Enum.reduce(0, fn i, acc -> i + acc end) @@ -16,13 +8,27 @@ defmodule Day1 do {nil, [0, 0, 0]} 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 {:add, n} -> apply_add(n, state) {:reset} -> apply_reset(state) 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 {current, total} = state new_current = n + if is_nil(current) do 0 else current end