From 899fcd9ca7313731ac3c9e43c33fdeb7dc5af37f Mon Sep 17 00:00:00 2001 From: Emerson Costa Date: Sun, 9 Oct 2022 14:41:57 -0300 Subject: [PATCH] chore: add public method to expose Compare behavior (#120) Co-authored-by: Emerson Costa Silva --- README.md | 5 +++++ money.go | 13 +++++++++++++ money_test.go | 21 +++++++++++++++++++++ 3 files changed, 39 insertions(+) diff --git a/README.md b/README.md index d97747d..d6429d6 100644 --- a/README.md +++ b/README.md @@ -73,6 +73,7 @@ Comparison * GreaterThanOrEqual * LessThan * LessThanOrEqual +* Compare Comparisons must be made between the same currency units. @@ -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 - diff --git a/money.go b/money.go index e735771..de58e89 100644 --- a/money.go +++ b/money.go @@ -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 +} diff --git a/money_test.go b/money_test.go index 196f5b5..0d9ac17 100644 --- a/money_test.go +++ b/money_test.go @@ -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) {