🗓️ Day 19Friday, 26 August 2022 - Day 19 of Exhort August 2022 - Exercism (My Elixir Journey)
Exercises
Need For Speed
Exercise on Exercism | View my solution
Solution
Expand to see code (spoiler alert)
Copy defmodule NeedForSpeed do
alias NeedForSpeed . Race
alias NeedForSpeed . RemoteControlCar , as: Car
import IO , only: [puts: 1 ]
import IO . ANSI , except: [color: 1 ]
def print_race (% Race {} = race) do
puts ( """
🏁 #{race . title} 🏁
Status: #{ Race . display_status (race)}
Distance: #{ Race . display_distance (race)}
Contestants:
""" )
race . cars
|> Enum . sort_by (&( - 1 * &1 . distance_driven_in_meters))
|> Enum . with_index ()
|> Enum . each ( fn {car , index} -> print_car (car , index + 1 ) end )
end
defp print_car (% Car {} = car , index) do
color = color (car)
puts ( """
#{index} . #{color}#{car . nickname}#{ default_color ()}
Distance: #{ Car . display_distance (car)}
Battery: #{ Car . display_battery (car)}
""" )
end
defp color (% Car {} = car) do
case car . color do
:red -> red ()
:blue -> cyan ()
:green -> green ()
end
end
end
View gist on GitHub
Notes
Interesting. Pretty short and fast. Learned a few things about aliases and imports. I still don't fully understand what is the difference between alias
and import
.
Overall progress