Elixir way to conditionally update a map

I’ve written a helper function for this sort of thing before

def maybe_put(map, _key, nil), do: map
def maybe_put(map, key, value), do: Map.put(map, key, value)

Then you can use for multiple fields and pipe easily, for example:

data = %{
  requireInteraction: true,
  title: title,
  icon: icon,
  click_action: click_action
}
|> maybe_put(:body, body)
|> maybe_put(:other_field, other_value)
26 Likes