Last active
September 26, 2017 06:23
-
-
Save kylethebaker/cc8ce665a2969481af9ab43ce6bb1085 to your computer and use it in GitHub Desktop.
Map diffs, golfed
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
# Compares two maps and generates a list of actions that can be applied to the | |
# first map to transform it into the second. | |
# | |
# diff = difference(m1, m2) | |
# apply(m1, diff) === m2 | |
defmodule MapDiffGolf do | |
def difference(%{} = m1, %{} = m2), do: | |
for {k, v} <- m2, | |
not match?(%{^k => ^v}, m1), | |
into: (for {k, _} <- m1, not Map.has_key?(m2, k), do: {:del, k}), | |
do: {:put, k, v} | |
def apply(%{} = m, [_|_] = d), do: | |
Enum.reduce d, m, fn | |
{:put, k, v}, m -> Map.put m, k, v | |
{:del, k}, m -> Map.delete m, k | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment