From 29506b5a044d16a96c8b972a710aa07595a556d1 Mon Sep 17 00:00:00 2001 From: Bel LaPointe Date: Wed, 25 Oct 2023 07:21:06 -0600 Subject: [PATCH] test balances push, pushall --- ledger/balances.go | 14 ++++++-------- ledger/balances_test.go | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 8 deletions(-) diff --git a/ledger/balances.go b/ledger/balances.go index b88f88a..d004304 100644 --- a/ledger/balances.go +++ b/ledger/balances.go @@ -12,15 +12,13 @@ type Balance map[Currency]float64 func (balances Balances) PushAll(other Balances) { for k, v := range other { if _, ok := balances[k]; !ok { - balances[k] = v - } else { - for k2, v2 := range v { - if _, ok := balances[k][k2]; !ok { - balances[k][k2] = v2 - } else { - balances[k][k2] += v2 - } + balances[k] = make(Balance) + } + for k2, v2 := range v { + if _, ok := balances[k][k2]; !ok { + balances[k][k2] = 0 } + balances[k][k2] += v2 } } } diff --git a/ledger/balances_test.go b/ledger/balances_test.go index d534f58..7d4e938 100644 --- a/ledger/balances_test.go +++ b/ledger/balances_test.go @@ -16,4 +16,39 @@ func TestBalances(t *testing.T) { t.Error(ba["z"]) } }) + + t.Run("pushall", func(t *testing.T) { + a := make(Balances) + a.Push(Delta{Name: "a", Currency: USD, Value: 0.1}) + a.Push(Delta{Name: "ab", Currency: USD, Value: 1.2}) + + b := make(Balances) + b.Push(Delta{Name: "b", Currency: USD, Value: 2.3}) + b.Push(Delta{Name: "ab", Currency: USD, Value: 3.4}) + + b.PushAll(a) + + if len(a) != 2 { + t.Error("modified original", len(a), a) + } + if a["a"][USD] != 0.1 { + t.Error("modified original a", a["a"]) + } + if a["ab"][USD] != 1.2 { + t.Error("modified original ab", a["ab"]) + } + + if len(b) != 3 { + t.Error("didnt union names", len(b), b) + } + if b["a"][USD] != 0.1 { + t.Error("didnt pull other unique", b["a"]) + } + if b["b"][USD] != 2.3 { + t.Error("didnt retain unique", b["b"]) + } + if b["ab"][USD] != 4.6 { + t.Error("didnt sum other", b["ab"]) + } + }) }