iT邦幫忙

2022 iThome 鐵人賽

DAY 27
0

Your community association has asked you to implement a simple registry application to manage the community garden registrations. The Plot struct has already been provided for you.

1. Open the garden

Implement the CommunityGarden.start/1 function, it should receive a optional keyword list of options to pass forward to the agent process. The garden's initial state should be initialized to represent an empty collection of plots. It should return an :ok tuple with the garden's pid.

2. List the registrations

Implement the CommunityGarden.list_registrations/1 function. It should receive the pid for the community garden. It should return a list of the stored plots that are registered.

At this point, we haven't added the ability to register a plot, so this list should be empty

3. Register plots to a person

Implement the CommunityGarden.register/2 function. It should receive the pid for the community garden and a name to register the plot. It should return the Plot struct with the plot's id and person registered to when it is successful.

The ids should be incremental and unique. You can keep an id counter in the agent's state.

4. Release plots

Implement the CommunityGarden.release/2 function. It should receive the pid and id of the plot to be released. It should return :ok on success. When a plot is released, the id is not re-used, it is used as a unique identifier only.

5. Get a registered plot

Implement the CommunityGarden.get_registration/2 function. It should receive the pid and id of the plot to be checked. It should return the plot if it is registered, and :not_found if it is unregistered.


https://exercism.org/tracks/elixir/exercises/community-garden

# 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(opts \\ []), do: Agent.start(fn -> [] end, opts)

  def list_registrations(pid),
    do:
      Agent.get(pid, fn state ->
        state |> Enum.filter(fn item -> !!item.plot_id end)
      end)

  def register(pid, register_to) do
    Agent.update(pid, fn state ->
      [%Plot{plot_id: (state |> length) + 1, registered_to: register_to} | state]
    end)

    Agent.get(pid, fn [head | _] -> head end)
  end

  def release(pid, plot_id) do
    Agent.update(pid, fn state ->
      state
      |> Enum.map(fn item ->
        if item.plot_id === plot_id,
          do: %Plot{plot_id: nil, registered_to: item.registered_to},
          else: item
      end)
    end)
  end

  def get_registration(pid, plot_id) do
    Agent.get(pid, fn state ->
      state |> Enum.find({:not_found, "plot is unregistered"}, fn item -> item.plot_id === plot_id end)
    end)
  end
end

上一篇
二十六. List Comprehensions
下一篇
二十八. Protocols
系列文
戀戀 Elixir30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言