diff --git a/lib/countries.ex b/lib/countries.ex index 67f3166..dabb85d 100644 --- a/lib/countries.ex +++ b/lib/countries.ex @@ -15,13 +15,25 @@ defmodule Countries do ## Examples iex> Countries.filter_by(:region, "Europe") [%Countries.Country{address_format: nil, alpha2: "VA" ... + + iex> Countries.filter_by(:names, "Reino Unido") + [%Countries.Country{address_format: nil, alpha2: "GB" ... """ def filter_by(attribute, value) do Enum.filter(countries(), fn(country) -> - Map.get(country, attribute) == value + Map.get(country, attribute) + |> equals_or_contains_in_list(value) end) end + defp equals_or_contains_in_list(attribute, value) when is_list(attribute) do + Enum.member?(attribute, value) + end + + defp equals_or_contains_in_list(attribute, value) do + attribute == value + end + @doc """ Checks if country for specific attribute and value exists. diff --git a/lib/data/countries/GB.yaml b/lib/data/countries/GB.yaml index b940a04..ac1ccd7 100755 --- a/lib/data/countries/GB.yaml +++ b/lib/data/countries/GB.yaml @@ -19,6 +19,7 @@ longitude: 2 00 W name: United Kingdom names: - United Kingdom +- The United Kingdom - Vereinigtes Königreich - Royaume-Uni - Reino Unido diff --git a/test/countries_test.exs b/test/countries_test.exs index ae64d6c..b553197 100644 --- a/test/countries_test.exs +++ b/test/countries_test.exs @@ -6,6 +6,19 @@ defmodule CountriesTest do assert Enum.count(country) == 1 end + test "filter countries by name" do + countries = Countries.filter_by(:name, "United Kingdom") + assert Enum.count(countries) == 1 + end + + test "filter countries by alternative names" do + countries = Countries.filter_by(:names, "Reino Unido") + assert Enum.count(countries) == 1 + + countries = Countries.filter_by(:names, "The United Kingdom") + assert Enum.count(countries) == 1 + end + test "filter many countries by region" do countries = Countries.filter_by(:region, "Europe") assert Enum.count(countries) == 51