Skip to content

Instantly share code, notes, and snippets.

@petros
Last active August 24, 2022 17:49
Show Gist options
  • Save petros/2476a9647535d8459a7b5f4973ec558a to your computer and use it in GitHub Desktop.
Save petros/2476a9647535d8459a7b5f4973ec558a to your computer and use it in GitHub Desktop.
Community Garden - Elixir - Exercism
defmodule Plot do
@enforce_keys [:plot_id, :registered_to]
defstruct [:plot_id, :registered_to]
end
defmodule CommunityGarden do
@spec start(Keyword.t()) :: tuple()
def start(opts \\ []) do
Agent.start(fn -> [] end, opts)
end
@spec list_registrations(pid()) :: list(Plot)
def list_registrations(pid) do
Agent.get(pid, fn state -> state end)
end
@spec register(pid(), String.t()) :: Plot
def register(pid, register_to) do
Agent.update(pid, fn state ->
[%Plot{plot_id: get_next_id(state), registered_to: register_to} | state]
end)
Agent.get(pid, fn state ->
[head | _tail] = state
head
end)
end
defp get_next_id([]), do: 1
defp get_next_id(plots), do: Enum.sort_by(plots, & &1.plot_id)
@spec release(pid(), integer()) :: :ok
def release(pid, plot_id) do
Agent.update(pid, fn state ->
Enum.filter(state, fn plot -> plot.plot_id != plot_id end)
end)
end
@spec get_registration(pid(), integer()) :: tuple() | Plot
def get_registration(pid, plot_id) do
plot =
Agent.get(pid, fn state ->
Enum.find(state, nil, fn plot -> plot.plot_id == plot_id end)
end)
cond do
plot == nil -> {:not_found, "plot is unregistered"}
true -> plot
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment