From 854863b8d6b03cb51aa2d5ba1a863e9896e5169f Mon Sep 17 00:00:00 2001 From: pedromcorreia <pedmcor@gmail.com> Date: Thu, 6 May 2021 22:00:31 -0300 Subject: [PATCH] Change the get function to let user find country by name --- lib/countries.ex | 30 ++++++++++++++++++++++++++---- test/countries_test.exs | 14 ++++++++++++-- 2 files changed, 38 insertions(+), 6 deletions(-) diff --git a/lib/countries.ex b/lib/countries.ex index 0fadb04..3f5895d 100644 --- a/lib/countries.ex +++ b/lib/countries.ex @@ -7,17 +7,39 @@ 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