Skip to content

Commit b04df88

Browse files
committed
perf: compute balances faster
1 parent 2d646de commit b04df88

File tree

1 file changed

+11
-23
lines changed

1 file changed

+11
-23
lines changed

balances.go

Lines changed: 11 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,6 @@ package ledger
33
import (
44
"slices"
55
"strings"
6-
7-
"github.com/howeyc/ledger/decimal"
86
)
97

108
// GetBalances provided a list of transactions and filter strings, returns account balances of
@@ -13,43 +11,33 @@ import (
1311
//
1412
// Accounts are sorted by name.
1513
func GetBalances(generalLedger []*Transaction, filterArr []string) []*Account {
16-
balances := make(map[string]decimal.Decimal)
17-
filters := len(filterArr) > 0
14+
var accList []*Account
15+
balances := make(map[string]*Account)
1816
for _, trans := range generalLedger {
1917
for _, accChange := range trans.AccountChanges {
20-
inFilter := false
21-
if filters {
22-
for i := 0; i < len(filterArr) && !inFilter; i++ {
23-
if strings.Contains(accChange.Name, filterArr[i]) {
24-
inFilter = true
25-
}
18+
inFilter := len(filterArr) == 0
19+
for i := 0; i < len(filterArr) && !inFilter; i++ {
20+
if strings.Contains(accChange.Name, filterArr[i]) {
21+
inFilter = true
2622
}
27-
} else {
28-
inFilter = true
2923
}
3024
if inFilter {
3125
accHier := strings.Split(accChange.Name, ":")
3226
accDepth := len(accHier)
3327
for currDepth := accDepth; currDepth > 0; currDepth-- {
3428
currAccName := strings.Join(accHier[:currDepth], ":")
35-
if ratNum, ok := balances[currAccName]; !ok {
36-
balances[currAccName] = accChange.Balance
29+
if acc, ok := balances[currAccName]; !ok {
30+
acc := &Account{Name: currAccName, Balance: accChange.Balance}
31+
accList = append(accList, acc)
32+
balances[currAccName] = acc
3733
} else {
38-
balances[currAccName] = ratNum.Add(accChange.Balance)
34+
acc.Balance = acc.Balance.Add(accChange.Balance)
3935
}
4036
}
4137
}
4238
}
4339
}
4440

45-
accList := make([]*Account, len(balances))
46-
count := 0
47-
for accName, accBalance := range balances {
48-
account := &Account{Name: accName, Balance: accBalance}
49-
accList[count] = account
50-
count++
51-
}
52-
5341
slices.SortFunc(accList, func(a, b *Account) int {
5442
return strings.Compare(a.Name, b.Name)
5543
})

0 commit comments

Comments
 (0)