Skip to content

Commit

Permalink
Added Kernel.then?/3 with a predicate parameter.
Browse files Browse the repository at this point in the history
  • Loading branch information
azizk committed Oct 15, 2023
1 parent 8a0961c commit dcbae1c
Showing 1 changed file with 22 additions and 1 deletion.
23 changes: 22 additions & 1 deletion lib/elixir/lib/kernel.ex
Original file line number Diff line number Diff line change
Expand Up @@ -2654,7 +2654,7 @@ defmodule Kernel do
Pipes the first argument, `value`, into the second argument, a function `fun`,
and returns the result of calling `fun`.
In other words, it invokes the function `fun` with `value` as argument,
In other words, it invokes the function `fun` with `value` as the argument,
and returns its result.
This is most commonly used in pipelines, using the `|>/2` operator, allowing you
Expand All @@ -2675,6 +2675,27 @@ defmodule Kernel do
end
end

@doc """
Pipes `value` into the given `fun` when `predicate` is truthy.
When the `predicate` is truthy `fun` will be called with `value`,
otherwise `value` is returned as is.
This is most commonly used in pipelines, allowing you
to pipe a value to a function outside of its first argument.
### Examples
iex> opts = [flag: true]
iex> 1 |> then?(opts[:flag], & &1 + 10)
11
"""
@doc since: "1.12.0"
defmacro then?(value, predicate, fun) do
quote bind_quoted: [value: value, predicate: predicate, fun: fun] do
if predicate, do: fun.(value), else: value
end
end

@doc """
Gets a value from a nested structure.
Expand Down

0 comments on commit dcbae1c

Please sign in to comment.