Show country emoji with elixir

Daniel Kukula - Jan 8 '22 - - Dev Community

Recently jorik posted about converting country code to flag emoji. I decided to give it a try in elixir.

My first attempt:

defmodule Flags do
  @flag_offset 127397
  def get_flag(country_code) do
    country_code
    |> String.upcase()
    |> String.split("", trim: true)  
    |> Enum.map(fn <<string::utf8>> -> <<(string + @flag_offset)::utf8>> end)
    |> Enum.join("")
  end
end

~w(us gb de pl) |> Enum.map(&Flags.get_flag()/1) |> Enum.join()
"馃嚭馃嚫馃嚞馃嚙馃嚛馃嚜馃嚨馃嚤"
Enter fullscreen mode Exit fullscreen mode

But can it be simplified? Sure it can:

defmodule Flags do
  @flag_offset 127397
  def get_flag(country_code) when byte_size(country_code) == 2 do
    <<s1::utf8, s2::utf8>> = String.upcase(country_code)  
    <<(s1 + @flag_offset)::utf8, (s2 + @flag_offset)::utf8>>
  end
  def get_flag(country_code), do: country_code
end

~w(us gb pl US) |> Enum.map(&Flags.get_flag()/1) |> Enum.join()
"馃嚭馃嚫馃嚞馃嚙馃嚨馃嚤馃嚭馃嚫"

Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . .