Jak zasugerował @Dogbert, możesz napisać funkcję rekurencyjnego scalania map.
defmodule MapUtils do
def deep_merge(left, right) do
Map.merge(left, right, &deep_resolve/3)
end
# Key exists in both maps, and both values are maps as well.
# These can be merged recursively.
defp deep_resolve(_key, left = %{}, right = %{}) do
deep_merge(left, right)
end
# Key exists in both maps, but at least one of the values is
# NOT a map. We fall back to standard merge behavior, preferring
# the value on the right.
defp deep_resolve(_key, _left, right) do
right
end
end
Oto niektóre przypadki testowe, aby dać wyobrażenie, jak konflikty są rozwiązywane:
ExUnit.start
defmodule MapUtils.Test do
use ExUnit.Case
test 'one level of maps without conflict' do
result = MapUtils.deep_merge(%{a: 1}, %{b: 2})
assert result == %{a: 1, b: 2}
end
test 'two levels of maps without conflict' do
result = MapUtils.deep_merge(%{a: %{b: 1}}, %{a: %{c: 3}})
assert result == %{a: %{b: 1, c: 3}}
end
test 'three levels of maps without conflict' do
result = MapUtils.deep_merge(%{a: %{b: %{c: 1}}}, %{a: %{b: %{d: 2}}})
assert result == %{a: %{b: %{c: 1, d: 2}}}
end
test 'non-map value in left' do
result = MapUtils.deep_merge(%{a: 1}, %{a: %{b: 2}})
assert result == %{a: %{b: 2}}
end
test 'non-map value in right' do
result = MapUtils.deep_merge(%{a: %{b: 1}}, %{a: 2})
assert result == %{a: 2}
end
test 'non-map value in both' do
result = MapUtils.deep_merge(%{a: 1}, %{a: 2})
assert result == %{a: 2}
end
end
Wielkie dzięki! – asiniy
Drobiazg, o którym należy pamiętać, jest to, że po cichu scalą one typy zdefiniowane przez strukturę/niestandardowe, a także wewnątrz są po prostu mapami. Aby tego uniknąć, możesz dopasować wzór do klucza '__struct__', który jest obecny, gdy jest to struktura. Aby uniknąć wpadnięcia w te pułapki, napisałem też bibliotekę [deep_merge] (https://github.com/PragTob/deep_merge). – PragTob