Created
June 22, 2018 16:53
-
-
Save mkreyman/a4e931fe687e827334c8560517812181 to your computer and use it in GitHub Desktop.
Find elements in given collections by pattern matching, i.e. all attachments in a POST request.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Find do | |
@moduledoc """ | |
Implements methods to find elements in given collections by pattern matching. | |
""" | |
@doc """ | |
Finds the first element in a list to match a given pattern. | |
""" | |
def first_match(collection) do | |
Enum.find(collection, fn(element) -> | |
match?({:fruit, _}, element) | |
end) | |
end | |
@doc """ | |
Finds all the elements in a list that match a given pattern. | |
""" | |
def all_matches(collection) do | |
Enum.filter(collection, fn(element) -> | |
match?({:fruit, _}, element) | |
end) | |
end | |
@doc """ | |
Finds all attachments in POST request. | |
""" | |
def find_attachments(params) do | |
Enum.filter(params, fn element -> | |
match?({_, %Plug.Upload{}}, element) | |
end) | |
|> Enum.map(fn {_, v} -> v end) | |
end | |
end | |
# And then, to test the implemented methods: | |
iex> require Find | |
iex> array = [{:fruit, "Apple"}, {:vegetable, "Carrot"}, {:fruit, "Orange"}] | |
iex> Find.first_match(array) | |
{:fruit, "Apple"} | |
iex> Find.all_matches(array) | |
[{:fruit, "Apple"}, {:fruit, "Orange"}] | |
iex> map = %{fruit: "Apple", vegetable: "Carrot"} | |
iex> Find.first_match(map) | |
{:fruit, "Apple"} | |
iex> Find.all_matches(map) | |
[{:fruit, "Apple"}] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment