Skip to content

Commit

Permalink
chore: add public method to expose Compare behavior (#120)
Browse files Browse the repository at this point in the history
Co-authored-by: Emerson Costa Silva <emerson@Emersons-MacBook-Pro.local>
  • Loading branch information
Trunkol and Emerson Costa Silva committed Oct 9, 2022
1 parent e9d346f commit 899fcd9
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 0 deletions.
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ Comparison
* GreaterThanOrEqual
* LessThan
* LessThanOrEqual
* Compare

Comparisons must be made between the same currency units.

Expand All @@ -84,6 +85,10 @@ twoEuros := money.New(200, money.EUR)
pound.GreaterThan(twoPounds) // false, nil
pound.LessThan(twoPounds) // true, nil
twoPounds.Equals(twoEuros) // false, error: Currencies don't match
twoPounds.Compare(pound) // 1, nil
pound.Compare(twoPounds) // -1, nil
pound.Compare(pound) // 0, nil
pound.Compare(twoEuros) // pound.amount, ErrCurrencyMismatch
```
Asserts
-
Expand Down
13 changes: 13 additions & 0 deletions money.go
Original file line number Diff line number Diff line change
Expand Up @@ -318,3 +318,16 @@ func (m *Money) UnmarshalJSON(b []byte) error {
func (m Money) MarshalJSON() ([]byte, error) {
return MarshalJSON(m)
}

// Compare function compares two money of the same type
// if m.amount > om.amount returns (1, nil)
// if m.amount == om.amount returns (0, nil
// if m.amount < om.amount returns (-1, nil)
// If compare moneys from distinct currency, return (m.amount, ErrCurrencyMismatch)
func (m *Money) Compare(om *Money) (int, error) {
if err := m.assertSameCurrency(om); err != nil {
return int(m.amount), err
}

return m.compare(om), nil
}
21 changes: 21 additions & 0 deletions money_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -611,6 +611,27 @@ func TestMoney_Comparison(t *testing.T) {
if r, err := pound.GreaterThanOrEqual(twoEuros); err == nil || r {
t.Error("Expected err")
}

if r, err := twoPounds.Compare(pound); r != 1 && err != nil {
t.Errorf("Expected %d Greater Than %d == %d got %d", pound.amount,
twoPounds.amount, 1, r)
}

if r, err := pound.Compare(twoPounds); r != -1 && err != nil {
t.Errorf("Expected %d Less Than %d == %d got %d", pound.amount,
twoPounds.amount, -1, r)
}

if _, err := pound.Compare(twoEuros); err != ErrCurrencyMismatch {
t.Error("Expected err")
}

anotherTwoEuros := New(200, EUR)
if r, err := twoEuros.Compare(anotherTwoEuros); r != 0 && err != nil {
t.Errorf("Expected %d Equals to %d == %d got %d", anotherTwoEuros.amount,
twoEuros.amount, 0, r)
}

}

func TestMoney_Currency(t *testing.T) {
Expand Down

0 comments on commit 899fcd9

Please sign in to comment.