Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adds Swiss.apply_if/3 and Swiss.apply_unless/3. #34

Merged
merged 1 commit into from Oct 27, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
50 changes: 50 additions & 0 deletions lib/swiss.ex
Expand Up @@ -36,6 +36,56 @@ defmodule Swiss do
value
end

@doc """
Applies the given `apply_fn` to the given `value` if the given `predicate_fn`
returns true.

By default, `predicate_fn` is `is_present/1`.

### Examples

iex> Swiss.apply_if(42, &(&1 + 8))
50

iex> Swiss.apply_if(42, &(&1 + 8), &(&1 > 40))
50

iex> Swiss.apply_if(42, &(&1 + 8), &(&1 < 40))
42
"""
@spec apply_if(value :: any(), apply_fn :: function(), predicate_fn :: function()) :: any()
def apply_if(val, apply_fn, predicate_fn \\ &is_present/1) do
if predicate_fn.(val),
do: apply_fn.(val),
else: val
end

@doc """
Applies the given `apply_fn` to the given `value` unless the given
`predicate_fn` returns true.

By default, `predicate_fn` is `is_nil/1`.

### Examples

iex> Swiss.apply_unless(nil, &(&1 + 8))
nil

iex> Swiss.apply_unless(42, &(&1 + 8))
50

iex> Swiss.apply_unless(42, &(&1 + 8), &(&1 > 40))
42

iex> Swiss.apply_unless(42, &(&1 + 8), &(&1 < 40))
50
"""
def apply_unless(val, apply_fn, predicate_fn \\ &is_nil/1) do
if predicate_fn.(val),
do: val,
else: apply_fn.(val)
end

@doc """
More idiomatic `!is_nil/1`.

Expand Down