ALN55Y45XQXCOZE3HEEXJGMNKJAJGC72C5RDVAR72J6N2YAGFRCQC
%{passport | height: hgt}
h =
case hgt do
<<a, b, c>> <> "cm" ->
{n, _} = Integer.parse(<<a, b, c>>)
if Enum.member?(150..193, n) do
{:ok, {n, :cm}}
else
{:error, "Height outside valid range: #{n}cm"}
end
<<a, b>> <> "in" ->
{n, _} = Integer.parse(<<a, b>>)
if Enum.member?(59..76, n) do
{:ok, {n, :inches}}
else
{:error, "Height outside valid range: #{n} inches"}
end
whatever ->
{:error, "Height not right: #{whatever}"}
end
case h do
{:ok, heit} -> {:ok, %{passport | height: heit}}
{:error, reason} -> {:error, reason}
end
%{passport | hair_color: hcl}
try do
["#", a, b, c, d, e, f] = String.graphemes(hcl)
n =
[a, b, c, d, e, f]
|> Enum.map(&String.to_integer(&1, 16))
n
|> Enum.map(&Enum.member?(0x0..0xF, &1))
|> Enum.all?(&Kernel.==(&1, true))
|> case do
true ->
s = n |> Enum.map(&Integer.to_string(&1, 16)) |> Enum.join()
{:ok, %{passport | hair_color: "##{s}"}}
end
rescue
_ -> {:error, "Not valid hair color: #{hcl}"}
end
# tests
%{birth_year: 2002} = Passport.parse_input("byr:2002")
%{birth_year: nil} = Passport.parse_input("byr:2003")
%{height: {60, :inches}} = Passport.parse_input("hgt:60in")
%{height: {190, :cm}} = Passport.parse_input("hgt:190cm")
%{height: nil} = Passport.parse_input("hgt:190in")
%{height: nil} = Passport.parse_input("hgt:190")
%{hair_color: "#123ABC"} = Passport.parse_input("hcl:#123abc")
%{hair_color: nil} = Passport.parse_input("hcl:#123abz")
%{hair_color: nil} = Passport.parse_input("hcl:123abc")