space_age with map and is_map_key guard
This commit is contained in:
parent
780dc17b36
commit
320bdc1286
|
@ -9,18 +9,21 @@ defmodule SpaceAge do
|
|||
| :uranus
|
||||
| :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
|
||||
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
|
||||
defguardp is_planet(planet) when is_map_key(@factors, planet)
|
||||
|
||||
@doc """
|
||||
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()}
|
||||
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),
|
||||
do: {:error, "not a planet"}
|
||||
|
|
Loading…
Reference in New Issue