DEV Community

chenge
chenge

Posted on

Cool CLIs in Elixir with IO.write/2

Today I read this, it told us with 3 simple and fun samples: clock, counter and progress bar.


defmodule Progress do
  @rounding_precision 2
  @progress_bar_size 50
  @complete_character "█"
  @incomplete_character "░"

  def bar(count, total) do
    percent = percent_complete(count, total)
    divisor = 100 / @progress_bar_size

    complete_count = round(percent / divisor)
    incomplete_count = @progress_bar_size - complete_count

    complete = String.duplicate(@complete_character, complete_count)
    incomplete = String.duplicate(@incomplete_character, incomplete_count)

    "#{complete}#{incomplete}  (#{percent}%)"
  end

  defp percent_complete(count, total) do
    Float.round(100.0 * count / total, @rounding_precision)
  end
end

total = 50

Enum.each(1..total, fn task ->
  IO.write("\r#{Progress.bar(task, total)}")
  Process.sleep(50)
end)

IO.write("\n")

Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
chenge profile image
chenge

works on my mac air.