From 2e135f2e8f6cf45c487ee5710aac1421c09e8fc6 Mon Sep 17 00:00:00 2001 From: bel Date: Sun, 15 Oct 2023 11:36:27 -0600 Subject: [PATCH] implement amount.go:Amount:AbsoluteValue --- digits-work-sample-go.d/amount.go | 7 ++++++ digits-work-sample-go.d/amount_test.go | 30 ++++++++++++++++++++++++++ 2 files changed, 37 insertions(+) diff --git a/digits-work-sample-go.d/amount.go b/digits-work-sample-go.d/amount.go index 31322fc..4ab6458 100644 --- a/digits-work-sample-go.d/amount.go +++ b/digits-work-sample-go.d/amount.go @@ -44,6 +44,13 @@ var localizedLanguagePrinter = func() *message.Printer { return message.NewPrinter(result) }() +func (amount Amount) AbsoluteValue() Amount { + if amount < 0 { + return -1.0 * amount + } + return amount +} + // Rounded rounds a float to the number of places specified. func (amount Amount) Rounded(places int) Amount { p := math.Pow10(places) diff --git a/digits-work-sample-go.d/amount_test.go b/digits-work-sample-go.d/amount_test.go index 464d553..a0311d0 100644 --- a/digits-work-sample-go.d/amount_test.go +++ b/digits-work-sample-go.d/amount_test.go @@ -87,3 +87,33 @@ func TestFormatUSD(t *testing.T) { }) } } + +func TestAmountAbsoluteValue(t *testing.T) { + cases := map[string]struct { + input Amount + want Amount + }{ + "zero": { + input: Amount(0.0), + want: Amount(0.0), + }, + "positive unchanged": { + input: Amount(1.0), + want: Amount(1.0), + }, + "negative unchanged": { + input: Amount(-0.000001), + want: Amount(0.000001), + }, + } + + for name, td := range cases { + tt := td // go bug through 1.21+ requires allocating a new variable or setting a go env for experimental features as of go 1.20 (1.21?) + t.Run(name, func(t *testing.T) { + got := tt.input.AbsoluteValue() + if got != tt.want { + t.Errorf("got \n\t%v, want\n\t%v", got, tt.want) + } + }) + } +}