Elixir Prelude v0.2.1 Prelude.Map

Functions operating on maps.

Summary

Functions

Appends to an array value in a map, creating one if the key does not exist

Turns all string map keys into atoms, leaving existing atoms alone (only top level)

To keep the API consistent also a way to get deep nested values. Works also with Stucts

Put an arbitrarily deep key into an existing map. Works also with Stucts

Remove a map key arbitrarily deep in a structure, similar to put_in Works also with Stucts

Group a map by an array of keys

Turns all atom map keys into strings, leaving existing strings alone (only top level)

Switch the keys with the values in a map

Converts strings to atoms, but leaves existing atoms alone

Functions

append_list(map, key, val)

Appends to an array value in a map, creating one if the key does not exist

atomify(map)

Turns all string map keys into atoms, leaving existing atoms alone (only top level)

deep_get(map, path)

To keep the API consistent also a way to get deep nested values. Works also with Stucts.

deep_put(map, path, val, variation \\ :map)

Put an arbitrarily deep key into an existing map. Works also with Stucts.

If you want to create lists as values, provide :list as last parameter.

If a value already exists at that level, it is turned into a list

For example:

# it works as expected with empty maps
iex> Prelude.Map.deep_put(%{}, [:a, :b, :c], "0")
%{a: %{b: %{c: "0"}}}

# when provided a deep path, all intermediate items are converted to maps
# this can lead to loss of data, eg:
# a.b.c = 1 is replaced by a map to make path a.b.c.d = 2 possible
iex> Prelude.Map.deep_put(%{a: %{b: %{c: "1"}}}, [:a, :b, :c, :d], "2")
%{a: %{b: %{c: %{d: "2"}}}}

# to collect values in a list, provide :list as last parameter.
iex> Prelude.Map.deep_put(%{a: %{b: %{c: "1"}}}, [:a, :b, :c, :d], "2", :list)
%{a: %{b: %{c: %{d: ["2"]}}}}

# to collect values in a list, provide :list as last parameter.
iex> Prelude.Map.deep_put(%{a: %{b: %{c: ["1"]}}}, [:a, :b, :c], "2", :list)
%{a: %{b: %{c: ["2", "1"]}}}
del_in(map, path)

Remove a map key arbitrarily deep in a structure, similar to put_in Works also with Stucts.

For example:

iex> a = %{a: %{b: %{c: %{d: 1, e: 1}}}}
...> Prelude.Map.del_in(a, [:a, :b, :c, :d])
%{a: %{b: %{c: %{e: 1}}}}
group_by(maps, groups)

Group a map by an array of keys

Provide a list of maps, and a list of keys to group by. All maps must have all the group_by fields, other fields can vary.

For example:

iex> Prelude.Map.group_by(
...>  [%{name: "stian", group: 1, cat: 2},
...>   %{name: "per",   group: 1, cat: 1}],
...>  [:group, :cat])
%{1 =>
  %{1 => [%{cat: 1, group: 1, name: "per"}],
    2 => [%{cat: 2, group: 1, name: "stian"}] } }
stringify(map)

Turns all atom map keys into strings, leaving existing strings alone (only top level)

switch(map)

Switch the keys with the values in a map

to_atom(x)

Converts strings to atoms, but leaves existing atoms alone