Qx.Map (qx v0.2.0)

View Source

Map helpers for reshaping nested data — recursive merging, key conversion between atoms and strings, and pruning empty values.

Summary

Functions

Recursively converts string keys to atoms, descending into nested maps and lists.

Drops every key whose value is nil.

Recursively merges right into left.

Recursively converts map keys to strings, descending into nested maps and lists.

Functions

atomize_keys(struct)

@spec atomize_keys(term()) :: term()

Recursively converts string keys to atoms, descending into nested maps and lists.

Only existing atoms are used. A key with no matching atom is left as a string, so untrusted input cannot exhaust the atom table.

Examples

iex> Qx.Map.atomize_keys(%{"a" => %{"b" => 1}})
%{a: %{b: 1}}

iex> Qx.Map.atomize_keys(%{"definitely_not_an_existing_atom_xyz" => 1})
%{"definitely_not_an_existing_atom_xyz" => 1}

compact(map, opts \\ [])

@spec compact(
  map(),
  keyword()
) :: map()

Drops every key whose value is nil.

Pass recursive: true to prune nested maps as well.

Examples

iex> Qx.Map.compact(%{a: 1, b: nil})
%{a: 1}

iex> Qx.Map.compact(%{a: %{b: nil, c: 2}}, recursive: true)
%{a: %{c: 2}}

deep_merge(left, right)

@spec deep_merge(map(), map()) :: map()

Recursively merges right into left.

When both sides hold a map under the same key the maps are merged; otherwise the value from right wins.

Examples

iex> Qx.Map.deep_merge(%{a: %{b: 1, c: 2}}, %{a: %{c: 3}})
%{a: %{b: 1, c: 3}}

iex> Qx.Map.deep_merge(%{a: 1}, %{b: 2})
%{a: 1, b: 2}

iex> Qx.Map.deep_merge(%{a: %{b: 1}}, %{a: "replaced"})
%{a: "replaced"}

stringify_keys(struct)

@spec stringify_keys(term()) :: term()

Recursively converts map keys to strings, descending into nested maps and lists.

Examples

iex> Qx.Map.stringify_keys(%{a: %{b: 1}})
%{"a" => %{"b" => 1}}

iex> Qx.Map.stringify_keys(%{list: [%{a: 1}]})
%{"list" => [%{"a" => 1}]}