View Source Lace.Map (Lace v0.0.2)
Extra sweets for Map
s
Summary
Functions
Moves the entry under old_key
to new_key
.
If there was a prexisting value under new_key
, it gets overwritten.
If old_key
is missing from the map, the map is returned unchanged.
Moves the value under old_key
to new_key
, unless new_key
already exists in the map.
Returns the map unchanged if old_key
is missing.
Puts the given value
in map
under key
if value
is non-nil
.
Conditionally adds a value to the map based on a predicate function.
Functions
Moves the entry under old_key
to new_key
.
If there was a prexisting value under new_key
, it gets overwritten.
If old_key
is missing from the map, the map is returned unchanged.
Examples
iex> Lace.Map.move(%{name: "Marie Curie", field: "Physics"}, :name, :full_name)
%{full_name: "Marie Curie", field: "Physics"}
iex> Lace.Map.move(%{1 => "desert", 2 => "lake"}, 2, 1)
%{1 => "lake"}
iex> Lace.Map.move(%{}, "status", "state")
%{}
Moves the value under old_key
to new_key
, unless new_key
already exists in the map.
Returns the map unchanged if old_key
is missing.
Examples
iex> Lace.Map.move_new(%{secondary: 20}, :secondary, :primary)
%{primary: 20}
iex> Lace.Map.move_new(%{primary: 10, secondary: 20}, :secondary, :primary)
%{primary: 10, secondary: 20}
Puts the given value
in map
under key
if value
is non-nil
.
Useful to conditionally add non-empty fields to maps, in a pipeline-friendly way and without having to do a second pass to reject fields with empty values.
If you need custom logic to decide whether to add the value,
use put_if/4
, which takes a predicate function.
Example
iex> fetch_user = fn _user_id -> nil end
...> fetch_project = fn project_id -> "project-" <> to_string(project_id) end
...>
...> %{}
...> |> Lace.Map.put_if(:user, fetch_user.(23))
...> |> Lace.Map.put_if(:project, fetch_project.(13))
%{project: "project-13"}
Conditionally adds a value to the map based on a predicate function.
This function is similar to put_if
, but allows for more complex
logic by using a predicate function that takes two parameters: the
current map and the value to be added. The predicate should return
a boolean indicating whether the value should be inserted into the map.
Examples
iex> Lace.Map.put_if(%{a: 1}, :b, 2 + 3, fn _map, n -> n > 4 end)
%{a: 1, b: 5}
iex> Lace.Map.put_if(%{a: 1}, :b, 2, fn _, _ -> :rand.uniform(3) < 5 end)
%{a: 1, b: 2}
iex> Lace.Map.put_if(%{a: 1}, :b, 2, fn _, _ -> :rand.uniform(3) > 5 end)
%{a: 1}