exercism/elixir/kindergarten-garden/lib/garden.ex

43 lines
1.2 KiB
Elixir

defmodule Garden do
@children ~w(alice bob charlie david eve fred ginny harriet ileana joseph kincaid larry)a
@plant_codes ~w(G C R V)
@plants %{
"G" => :grass,
"C" => :clover,
"R" => :radishes,
"V" => :violets
}
defguardp is_plant_code(char) when char in @plant_codes
defp plant(char) when is_plant_code(char), do: Map.get(@plants, char)
defp student_plants({name, position}, info_string) do
plants = info_string
|> String.split("\n")
|> Enum.map_join(&String.slice(&1, position * 2, 2))
|> String.graphemes()
|> Enum.map(&plant/1)
|> List.to_tuple()
{name, plants}
end
@doc """
Accepts a string representing the arrangement of cups on a windowsill and a
list with names of students in the class. The student names list does not
have to be in alphabetical order.
It decodes that string into the various gardens for each student and returns
that information in a map.
"""
@spec info(String.t(), list) :: map
def info(info_string, student_names \\ @children) do
student_names
|> Enum.sort()
|> Enum.with_index()
|> Enum.map(&student_plants(&1, info_string))
|> Enum.into(%{})
end
end