Skip to content

Instantly share code, notes, and snippets.

@mkreyman
Created June 22, 2018 16:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mkreyman/a4e931fe687e827334c8560517812181 to your computer and use it in GitHub Desktop.
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.
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