CommonX v0.0.5 EnumX View Source

Some enumeration extensions.

Link to this section Summary

Functions

Returns a list where each item is the result of invoking fun on each corresponding item of enumerable. For maps, the function expects a key-value tuple

Reduces the enumerable until fun returns {:error, reason}

Link to this section Functions

Link to this function

map(enumerable, fun) View Source
map(Enum.t(), (Enum.element() -> {:ok, any()} | {:error, any()})) ::
  {:ok, list()} | {:error, any()}

Returns a list where each item is the result of invoking fun on each corresponding item of enumerable. For maps, the function expects a key-value tuple.

Examples

iex> EnumX.map([1, 2, 3], fn x -> {:ok, x * 2} end)
{:ok, [2, 4, 6]}
iex> EnumX.map([a: 1, b: 2], fn {k, v} -> {:ok, {k, -v}} end)
{:ok, [a: -1, b: -2]}
Link to this function

reduce_while(enumerable, acc, fun) View Source
reduce_while(
  Enum.t(),
  any(),
  (Enum.element(), any() -> {:ok, any()} | {:error, any()})
) :: {:ok, any()} | {:error, any()}

Reduces the enumerable until fun returns {:error, reason}.

The return value for fun is expected to be

  • {:ok, acc} to continue the reduction with acc as the new accumulator or
  • {:error, acc} to halt the reduction and return acc as the return value of this function

Examples

iex> EnumX.reduce_while(1..100, 0, fn x, acc ->
...>   if x < 3, do: {:ok, acc + x}, else: {:error, acc}
...> end)
{:error, 3}