DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Daniel Kukula
Daniel Kukula

Posted on

Show country emoji with elixir

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

Top comments (0)

Timeless DEV post...

How to write a kickass README

Arguably the single most important piece of documentation for any open source project is the README. A good README not only informs people what the project does and who it is for but also how they use and contribute to it.

If you write a README without sufficient explanation of what your project does or how people can use it then it pretty much defeats the purpose of being open source as other developers are less likely to engage with or contribute towards it.