diff --git a/lib/countries.ex b/lib/countries.ex index 198aa6f..c7fe6e8 100644 --- a/lib/countries.ex +++ b/lib/countries.ex @@ -11,18 +11,40 @@ defmodule Countries do end @doc """ - Returns one country given is alpha2 country code. + Returns one country by given name ## Examples - iex> %Countries.Country{name: name} = Countries.get("PL") + iex> %Countries.Country{alpha2: alpha2} = Countries.get("Poland") + iex> alpha2 + "PL" + """ + + def get(attrs) when is_bitstring(attrs) do + country = filter_by(:name, attrs) + + case length(country) do + 0 -> + [] + + 1 -> + List.first(country) + end + end + + @doc """ + Returns one country by given alpha2 country code + + ## Examples + + iex> %Countries.Country{name: name} = Countries.get_by_alpha2("PL") iex> name "Poland" """ - def get(country_code) do - [country] = filter_by(:alpha2, country_code) + def get_by_alpha2(attrs) when bit_size(attrs) == 16 do + [country] = filter_by(:alpha2, attrs) country end diff --git a/test/countries_test.exs b/test/countries_test.exs index 7c94dc1..4c68723 100644 --- a/test/countries_test.exs +++ b/test/countries_test.exs @@ -10,8 +10,18 @@ defmodule CountriesTest do end describe "get/1" do - test "gets one country" do - %{alpha2: "GB"} = Countries.get("GB") + test "gets one country by country name" do + %{alpha2: "BR"} = Countries.get("Brazil") + end + + test "gets empty string with invalid country name" do + [] = Countries.get("Bra") + end + end + + describe "get_by_alpha2/1" do + test "gets one country by country code" do + %{alpha2: "GB"} = Countries.get_by_alpha2("GB") end end