AbsintheUtils.Internal.MapHelpers (absinthe_utils v0.0.1-main-413ca15b56c2636667dc5f1b7898f81da11032b0)

View Source

Helper for nested map manipulations.

Summary

Functions

Put a value in a tested map, if any of the keys in the keys_path are not found, they will be recursively created.

Pop a key from a nested map, if successful returns a tuple of

Functions

recursive_put_in(map, keys_path, value)

Put a value in a tested map, if any of the keys in the keys_path are not found, they will be recursively created.

Examples

iex> MapHelpers.recursive_put_in(%{a: 1}, [:b], 2)
%{a: 1, b: 2}

iex> MapHelpers.recursive_put_in(%{}, [:a], 1)
%{a: 1}

iex> MapHelpers.recursive_put_in(%{}, :a, 1)
%{a: 1}

safe_pop_in(map, last_key)

Pop a key from a nested map, if successful returns a tuple of:

  • the popped value
  • the modified map, without the popped key OR if the key is not found, returns :error

Examples

iex> MapHelpers.safe_pop_in(%{a: 1}, [:a])
{1, %{}}

iex> MapHelpers.safe_pop_in(%{a: 1}, :a)
{1, %{}}

iex> MapHelpers.safe_pop_in(%{a: 1}, [:invalid])
:error

iex> MapHelpers.safe_pop_in(%{a: %{b: 1}}, [:a, :b])
{1, %{a: %{}}}

iex> MapHelpers.safe_pop_in(%{a: %{b: 1}}, [:a, :invalid])
:error

iex> MapHelpers.safe_pop_in(%{}, [:a])
:error

iex> MapHelpers.safe_pop_in(%{a: 1}, [])
:error

iex> MapHelpers.safe_pop_in(%{a: 1}, [:a, :b, :c])
:error

iex> MapHelpers.safe_pop_in(%{a: 1, b: %{c: 2}}, [:b])
{%{c: 2}, %{a: 1}}

iex> MapHelpers.safe_pop_in(%{"a" => 1}, ["a"])
{1, %{}}