Skip to content

Instantly share code, notes, and snippets.

@narrowtux
Last active November 15, 2016 08:04
Show Gist options
  • Save narrowtux/f7ac210ba12736c4ad6fe4315ba87edb to your computer and use it in GitHub Desktop.
Save narrowtux/f7ac210ba12736c4ad6fe4315ba87edb to your computer and use it in GitHub Desktop.
remove and difference functions for Enum
defmodule Coll do
@doc """
Removes all values from the subject
iex> Coll.remove([1, 2, 3], [2, 3])
[1]
iex> Coll.remove([1, 2], [2, 3, 4])
[1]
"""
def remove(subject, values) do
subject
|> Enum.filter(fn left -> !Enum.member?(values, left) end)
end
@doc """
Shows which elements were added and which were removed in 2 versions of a collection.
Returns a tuple with a collection of removed values and a collection of added values
## Examples
### Compare lists
iex> old = ["apple", "banana", "pear"]
iex> new = ["tomato", "apple"]
iex> {removed, added} = Coll.difference(old, new)
iex> removed
["banana", "pear"]
iex> added
["tomato"]
This tells us that "banana" and "pear" have been removed, while "tomato" has been added.
### Compare keyword lists
iex> old = [fruit: :apple, vegetable: :cucumber]
iex> new = [fruit: :apple, vegetable: :potato]
iex> {removed, added} = Coll.difference(old, new)
iex> removed
[vegetable: :cucumber]
iex> added
[vegetable: :potato]
### Maps are special
iex> old = %{}
iex> new = %{foo: "bar"}
iex> {removed, added} = Coll.difference(old, new)
iex> removed
[]
iex> added
[foo: "bar"]
### Deep comparision
iex> old = [[1, 2, 3], [4, 5, 6]]
iex> new = [[2, 3, 4], [4, 6]]
iex> old |> Enum.zip(new) |> Enum.map(fn {old, new} -> Coll.difference(old, new) end)
[
{[1], [4]},
{[5], []}
]
"""
def difference(old, new) do
{remove(old, new), remove(new, old)}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment