Skip to content

Commit

Permalink
Add Decimal.apply_context/1 and deprecate Decimal.plus/1 (ericmj#135)
Browse files Browse the repository at this point in the history
  • Loading branch information
wojtekmach authored Dec 23, 2019
1 parent 1a60c70 commit 81f1e1f
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 9 deletions.
15 changes: 12 additions & 3 deletions lib/decimal.ex
Original file line number Diff line number Diff line change
Expand Up @@ -939,12 +939,21 @@ defmodule Decimal do
def negate(%Decimal{sign: sign} = num), do: context(%{num | sign: -sign})
def negate(num), do: negate(decimal(num))

@doc false
@deprecated "Use Decimal.apply_context/1 instead"
def plus(decimal) do
apply_context(decimal)
end

@doc """
Applies the context to the given number rounding it to specified precision.
"""
@spec plus(t) :: t
def plus(%Decimal{coef: :sNaN} = num), do: error(:invalid_operation, "operation on NaN", num)
def plus(%Decimal{} = num), do: context(num)
doc_since("1.9.0")
@spec apply_context(t) :: t
def apply_context(%Decimal{coef: :sNaN} = num),
do: error(:invalid_operation, "operation on NaN", num)

def apply_context(%Decimal{} = num), do: context(num)

@doc """
Check if given number is positive
Expand Down
12 changes: 6 additions & 6 deletions test/decimal_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -468,16 +468,16 @@ defmodule DecimalTest do
end
end

test "plus/1" do
test "apply_context/1" do
Decimal.with_context(%Context{precision: 2}, fn ->
assert Decimal.plus(~d"0") == d(1, 0, 0)
assert Decimal.plus(~d"5") == d(1, 5, 0)
assert Decimal.plus(~d"123") == d(1, 12, 1)
assert Decimal.plus(~d"nan") == d(1, :qNaN, 0)
assert Decimal.apply_context(~d"0") == d(1, 0, 0)
assert Decimal.apply_context(~d"5") == d(1, 5, 0)
assert Decimal.apply_context(~d"123") == d(1, 12, 1)
assert Decimal.apply_context(~d"nan") == d(1, :qNaN, 0)
end)

assert_raise Error, fn ->
Decimal.plus(~d"snan")
Decimal.apply_context(~d"snan")
end
end

Expand Down

0 comments on commit 81f1e1f

Please sign in to comment.