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

Add public method to expose Compare behavior #120

Merged
merged 1 commit into from
Oct 9, 2022
Merged
Show file tree
Hide file tree
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
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