Skip to content

Commit

Permalink
Filter by names (#19)
Browse files Browse the repository at this point in the history
* filter_by/2 can now be used to search in list attributes like :names

* add alternative name for GB
  • Loading branch information
jaimeiniesta authored and SebastianSzturo committed Oct 7, 2017
1 parent a20f8ef commit c978230
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 1 deletion.
14 changes: 13 additions & 1 deletion lib/countries.ex
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
1 change: 1 addition & 0 deletions lib/data/countries/GB.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ longitude: 2 00 W
name: United Kingdom
names:
- United Kingdom
- The United Kingdom
- Vereinigtes Königreich
- Royaume-Uni
- Reino Unido
Expand Down
13 changes: 13 additions & 0 deletions test/countries_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit c978230

Please sign in to comment.