recursionelixirupdateskey-valuenested-map

in a nested map find key and update its value


find key : sum in nested map and update its value to : bill * 100 + : coins

Need to pass test1

test "test1" do
  assert BcToInt.data(%{
            count: 3,
            sum: %{bills: 1, coins: 99},
            tax: %{count: 3, sum: %{bills: 1, coins: 1}}
          }) ==
            %{count: 3, sum: 199, tax: %{count: 3, sum: 101}}
end

I tried to do it using Map_replace() and checking value for nested map using is_map and call function again if true but how to get end result

def data(xmap) do
  Enum.map(xmap, fn {_key, value} ->
    keyy = :sum

    aa = List.first(Map.values(xmap[keyy])) * 100 + List.last(Map.values(xmap[keyy]))

    if Map.has_key?(xmap, keyy) do
      Map.replace(xmap, keyy, aa)

      if is_map(value) do
        data1(value)
      end
    end
  end)
end

Solution

  • Here's a version without using external libraries:

    def data(map) do
      map =
        case map[:sum] do
          %{bills: bills, coins: coins} -> %{map | sum: bills * 100 + coins}
          _ -> map
        end
    
      Map.new(map, fn
        {k, v} when is_map(v) -> {k, data(v)}
        entry -> entry
      end)
    end
    

    Usage:

    iex(1)> data = ...
    %{
      count: 3,
      sum: %{bills: 1, coins: 99},
      tax: %{count: 3, sum: %{bills: 1, coins: 1}}
    }
    iex(2)> BcToInt.data(data)
    %{count: 3, sum: 199, tax: %{count: 3, sum: 101}}