Elixir
  • My Elixir journey
  • Why functional programming?
  • Exhort
    • 🗓️Day 22
    • 🗓️Day 21
    • 🗓️Day 20
    • 🗓️Day 19
    • 🗓️Day 18
    • 🗓️Day 17
    • 🗓️Day 16
    • 🗓️Day 15
    • 🗓️Day 14
  • Bits and pieces
    • Clean mix dependencies
    • Run tests automatically on save
    • Run tests and stop on first failure
    • How to remove Tailwind from a Phoenix project
Powered by GitBook
On this page
  • Exercises
  • Need For Speed
  • Overall progress
  1. Exhort

Day 19

Friday, 26 August 2022 - Day 19 of Exhort August 2022 - Exercism (My Elixir Journey)

PreviousDay 20NextDay 18

Last updated 2 years ago

Exercises

Need For Speed

|

Solution

Expand to see code (spoiler alert)
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

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

🗓️
Exercise on Exercism
View my solution
View gist on GitHub
Need For Speed
Progress
An image showing my progress on Exercism. It's 21.2% as of Friday, 26 August 2022.