space_age with map and is_map_key guard

This commit is contained in:
Danil Negrienko 2024-06-29 03:47:30 -04:00
parent 780dc17b36
commit 320bdc1286
1 changed files with 14 additions and 11 deletions

View File

@ -9,18 +9,21 @@ defmodule SpaceAge do
| :uranus | :uranus
| :neptune | :neptune
@planets ~w(mercury venus earth mars jupiter saturn uranus neptune)a @type factors :: %{planet => float}
@factors %{
mercury: 0.2408467,
venus: 0.61519726,
earth: 1.0,
mars: 1.8808158,
jupiter: 11.862615,
saturn: 29.447498,
uranus: 84.016846,
neptune: 164.79132
}
defguardp is_planet(planet) when planet in @planets @seconds_in_year 31_557_600
defp factor(:mercury), do: 0.2408467 defguardp is_planet(planet) when is_map_key(@factors, planet)
defp factor(:venus), do: 0.61519726
defp factor(:earth), do: 1.0
defp factor(:mars), do: 1.8808158
defp factor(:jupiter), do: 11.862615
defp factor(:saturn), do: 29.447498
defp factor(:uranus), do: 84.016846
defp factor(:neptune), do: 164.79132
@doc """ @doc """
Return the number of years a person that has lived for 'seconds' seconds is Return the number of years a person that has lived for 'seconds' seconds is
@ -28,7 +31,7 @@ defmodule SpaceAge do
""" """
@spec age_on(planet, pos_integer) :: {:ok, float} | {:error, String.t()} @spec age_on(planet, pos_integer) :: {:ok, float} | {:error, String.t()}
def age_on(planet, seconds) when is_planet(planet), def age_on(planet, seconds) when is_planet(planet),
do: {:ok, seconds / (factor(planet) * 31_557_600)} do: {:ok, seconds / (@factors[planet] * @seconds_in_year)}
def age_on(_planet, _seconds), def age_on(_planet, _seconds),
do: {:error, "not a planet"} do: {:error, "not a planet"}