Skip to content

Instantly share code, notes, and snippets.

@alco
Created January 3, 2016 21:49
Show Gist options
  • Save alco/890195e7a3bf5f951129 to your computer and use it in GitHub Desktop.
Save alco/890195e7a3bf5f951129 to your computer and use it in GitHub Desktop.
defmodule MapContainment do
def contains?(supermap, submap) do
# Convert the submap into a list of key-value pairs where each key
# is a list representing the keypath of its corresponding value.
flatten_with_list_keys(submap)
# Check that every keypath has the same value in both maps
# (assumes that `nil` is not a legitimate value)
|> Enum.all?(fn {keypath, val} when val != nil ->
get_in(supermap, keypath) == val
end)
end
defp flatten_with_list_keys(map) do
Enum.flat_map(map, fn
{key, map} when is_map(map) ->
for {subkey, val} <- flatten_with_list_keys(map), do: {[key | subkey], val}
{key, val} ->
[{[key], val}]
end)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment