Show Country Emoji with Elixir

Show Country Emoji with Elixir

Table of Contents

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()
"πŸ‡ΊπŸ‡ΈπŸ‡¬πŸ‡§πŸ‡©πŸ‡ͺπŸ‡΅πŸ‡±"

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()
"πŸ‡ΊπŸ‡ΈπŸ‡¬πŸ‡§πŸ‡΅πŸ‡±πŸ‡ΊπŸ‡Έ"
comments powered by Disqus

Related Posts

Porting Files Generated by Phoenix to Surface

Porting Files Generated by Phoenix to Surface

This post is intended to get you started with surface provided components. I provided the original code and surface versions so you can compare the differences yourself without installing anything.

Read More
Serving Open Street Map Vector Tiles with Elixir and Phoenix

Serving Open Street Map Vector Tiles with Elixir and Phoenix

Some background on mbtiles files from mapbox/mbtiles-spec

MBTiles is a specification for storing tiled map data in SQLite databases for immediate usage and for transfer. … The metadata table is used as a key/value store for settings. It MUST contain these two rows:

Read More
Machine Learning on Ryzen 7840HS

Machine Learning on Ryzen 7840HS

I bought an AMD laptop with 7840hs and 32GB RAM with the hope that I can play with machine learning models. At the beginning it was problematic, I could not get anything bigger to work but after some time spent reading and experimenting here are some of my findings.

Read More