Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion lib/oxide.ex
Original file line number Diff line number Diff line change
Expand Up @@ -184,17 +184,26 @@ defmodule Oxide.Result do
@doc ~S"""
Convert a maybe-nil value to a result.

Maps `nil` to `{:error, reason}` and any non-`nil` value to `{:ok, value}`.
Maps `nil` and `{:ok, nil}` to `{:error, reason}`, passes errors through and otherwise maps `value`, or {:ok, value}` to `{:ok, value}`.

iex> %{"key" => "value"} |> Map.get("key") |> Result.err_if_nil(:notfound)
{:ok, "value"}
iex> %{"key" => "value"} |> Map.get("missing") |> Result.err_if_nil(:notfound)
{:error, :notfound}
iex> {:ok, nil} |> Result.err_if_nil(:notfound)
{:error, :notfound}
iex> {:ok, "value"} |> Result.err_if_nil(:notfound)
{:ok, "value"}
iex> {:error, :badthing} |> Result.err_if_nil(:notfound)
{:error, :badthing}

"""
@spec err_if_nil(any(), any()) :: t()
def err_if_nil(value, reason)
def err_if_nil(value, reason) when is_nil(value), do: {:error, reason}
def err_if_nil({:ok, value}, reason) when is_nil(value), do: {:error, reason}
def err_if_nil({:ok, value}, _reason) when not is_nil(value), do: {:ok, value}
def err_if_nil({:error, reason}, _reason), do: {:error, reason}
def err_if_nil(value, _reason) when not is_nil(value), do: {:ok, value}

@doc ~S"""
Expand Down