exercism/elixir/community-garden/lib/community_garden.ex

39 lines
1.1 KiB
Elixir

# Use the Plot struct as it is provided
defmodule Plot do
@enforce_keys [:plot_id, :registered_to]
defstruct [:plot_id, :registered_to]
end
defmodule CommunityGarden do
def start(),
do: Agent.start(fn -> %{index: 0, plots: []} end)
def list_registrations(pid),
do: Agent.get(pid, fn %{plots: plots} -> plots end)
def register(pid, register_to),
do:
Agent.get_and_update(pid, fn %{plots: plots, index: counter} ->
index = counter + 1
plot = %Plot{plot_id: index, registered_to: register_to}
{plot, %{plots: [plot | plots], index: index}}
end)
def release(pid, plot_id),
do:
Agent.cast(pid, fn %{plots: plots} = state ->
%{state | plots: Enum.reject(plots, fn element -> compare(element, plot_id) end)}
end)
def get_registration(pid, plot_id) do
list_registrations(pid)
|> Enum.find(
{:not_found, "plot is unregistered"},
fn element -> compare(element, plot_id) end
)
end
defp compare(%Plot{plot_id: element_id}, plot_id) when element_id == plot_id, do: true
defp compare(_element, _plot_id), do: false
end