Repair deeply neested map

Hi everone. Since a while i am trying to wrap my head around Recursion in Elixir and deeply nested maps.

I do have two maps that may contain lists, other maps or primitive data types.

  • One map serves as a template and contains a default structure with default values.
  • The other one contains data that should have the same structure but may deviate in the values

I do like to write a function def repair(map, template) that returns a ‘repaired’ map by:

  • removing keys not present in the template
  • adding keys present in the template but not in map using the template’s default values.
  • keys present in both the map and template should take the values of the map.

Here is an example:

map = %{name: "John", address: %{town: "Springfield"}, skills: [2, 3, 1], initials: "JH"}

template = %{name: "", address: %{street: nil, town: nil}, skills: [], age: nil}

>>> repair(map, template)
%{name: "John", address: %{street: nil, town: "Springfield"}, skills: [2, 3, 1], age: nil}

Any help would be much appriciated!

Hello :slight_smile:

try to repair your maps with this implementation

def repair(map, template) do
  Map.new(template, fn
    {key, default_value} when is_map(default_value) ->
      {key, repair(Map.get(map, key, %{}), default_value)}

    {key, default_value} ->
      {key, Map.get(map, key, default_value)}
  end)
end
6 Likes

@ fuelen
Thanks so much. This is exactly what I needed. Still amazed with how little code this could be archived!