clean up runner

This commit is contained in:
Caleb Webber 2023-10-29 01:47:54 -04:00
parent bac2473cd9
commit c9ff65d949

View file

@ -1,28 +1,36 @@
defmodule AOCRunner do
defp is_empty(s) do
(s |> String.trim() |> String.length()) == 0
@spec is_empty?(s :: String.t()) :: boolean()
defp is_empty?(s) do
String.trim(s) |> String.length() == 0
end
def run(advent, part) do
{_, state} = IO.stream() |>
Enum.reduce_while(
{nil, advent.init_state(part)},
fn line, acc -> line
|> then(fn line ->
{u, state} = acc
{u, advent.execute(line, state)}
end)
|> then(fn {u, s} ->
if (line |> is_empty()) && (u |> is_empty()) do
{:halt, {u, s}}
else
{:cont, {u, s}}
end
end)
|> then(fn {reduce_atom, {_, state}} -> {reduce_atom, {String.trim(line), state}} end)
end
)
@spec both_empty?(a :: String.t(), b :: String.t()) :: boolean()
defp both_empty?(a, b) do
is_empty?(a) && is_empty?(b)
end
IO.puts(advent.get_answer(state))
@spec run(advent :: Advent, part :: :part1 | :part2) :: nil
def run(advent, part) do
# runs the advent execute method with the current line,
# until two empty lines are sent
run_until_exit = fn line, acc ->
{_, state} = acc
put_elem(acc, 1, advent.execute(line, state)) |>
then(fn {last_line, s} ->
{(if both_empty?(line, last_line), do: :halt, else: :cont), {String.trim(line), s}}
end)
end
IO.stream() |>
Enum.reduce_while(
{nil, advent.init_state(part)},
&run_until_exit.(&1, &2)) |>
elem(1) |>
advent.get_answer() |>
IO.puts()
nil
end
end