balances.Group

main
bel 2024-07-20 09:46:19 -06:00
parent b6c6e83443
commit 6d174b031b
2 changed files with 52 additions and 0 deletions

View File

@ -22,6 +22,29 @@ func (balances Balances) Like(pattern string) Balances {
return result
}
func (balances Balances) Group(pattern string) Balances {
result := make(Balances)
p := regexp.MustCompile(pattern)
for k, v := range balances {
k2 := p.FindString(k)
if k2 == "" {
k2 = k
}
was := result[k2]
if was == nil {
was = make(Balance)
}
for k3, v3 := range v {
was[k3] += v3
}
result[k2] = was
}
return result
}
func (balances Balances) WithBPIs(bpis BPIs) Balances {
return balances.WithBPIsAt(bpis, "9")
}

View File

@ -51,4 +51,33 @@ func TestBalances(t *testing.T) {
t.Error("didnt sum other", b["ab"])
}
})
t.Run("like", func(t *testing.T) {
was := make(Balances)
was.Push(Delta{Name: "a", Currency: USD, Value: 0.1})
was.Push(Delta{Name: "ab", Currency: USD, Value: 1.2})
got := was.Like(`^ab$`)
if len(got) != 1 || got["ab"][USD] != 1.2 {
t.Error(got)
}
})
t.Run("group", func(t *testing.T) {
was := make(Balances)
was.Push(Delta{Name: "a:1", Currency: USD, Value: 0.1})
was.Push(Delta{Name: "a:2", Currency: USD, Value: 1.2})
was.Push(Delta{Name: "b:1", Currency: USD, Value: 2.2})
got := was.Group(`^[^:]*`)
if len(got) != 2 {
t.Error(got)
}
if got["a"][USD] != 1.3 {
t.Error(got)
}
if got["b"][USD] != 2.2 {
t.Error(got)
}
})
}