View Source Bunch.Map (Bunch v1.6.1)

A bunch of helper functions for manipulating maps.

Summary

Functions

Updates value at key in map and returns new value and updated map.

Works like get_updated/3, but requires map to contain key.

Maps keys of map using function f.

Maps values of map using function f.

Moves value stored at old_key to new_key.

Works like move/3, but fails if either old_key is absent or new_key is present in map.

Functions

Link to this function

get_updated(map, key, fun)

View Source
@spec get_updated(map(), Map.key(), (Map.value() -> v)) :: {v, map()}
when v: Map.value()

Updates value at key in map and returns new value and updated map.

Uses Map.get_and_update/3 under the hood.

Example

iex> %{a: 1} |> Bunch.Map.get_updated(:a, & &1+1)
{2, %{a: 2}}
Link to this function

get_updated!(map, key, fun)

View Source
@spec get_updated!(map(), Map.key(), (Map.value() -> v)) :: {v, map()}
when v: Map.value()

Works like get_updated/3, but requires map to contain key.

Uses Map.get_and_update!/3 under the hood.

Example

iex> %{a: 1} |> Bunch.Map.get_updated!(:a, & &1+1)
{2, %{a: 2}}
@spec map_keys(%{required(k1) => v}, (k1 -> k2)) :: %{required(k2) => v}
when k1: any(), k2: any(), v: any()

Maps keys of map using function f.

Example

iex> Bunch.Map.map_keys(%{1 => :a, 2 => :b}, & &1+1)
%{2 => :a, 3 => :b}
@spec map_values(%{required(k) => v1}, (v1 -> v2)) :: %{required(k) => v2}
when k: any(), v1: any(), v2: any()

Maps values of map using function f.

Example

iex> Bunch.Map.map_values(%{a: 1, b: 2}, & &1+1)
%{a: 2, b: 3}
Link to this function

move(map, old_key, new_key, default_value)

View Source
@spec move(%{required(k) => v}, old_key :: k, new_key :: k, default_value :: v) :: %{
  required(k) => v
}
when k: any(), v: any()

Moves value stored at old_key to new_key.

If old_key is not present in map, default_value is stored at new_key. If new_key is present in map, it's value is overwritten.

Examples

iex> Bunch.Map.move(%{a: 1, b: 2}, :a, :c, 3)
%{b: 2, c: 1}
iex> Bunch.Map.move(%{a: 1, b: 2}, :a, :b, 3)
%{b: 1}
iex> Bunch.Map.move(%{a: 1, b: 2}, :c, :b, 3)
%{a: 1, b: 3}
Link to this function

move!(map, old_key, new_key)

View Source
@spec move!(%{required(k) => v}, old_key :: k, new_key :: k) ::
  %{required(k) => v} | no_return()
when k: any(), v: any()

Works like move/3, but fails if either old_key is absent or new_key is present in map.

Example

iex> Bunch.Map.move!(%{a: 1, b: 2}, :a, :c)
%{b: 2, c: 1}