-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathledger.go
77 lines (67 loc) · 1.29 KB
/
ledger.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package main
import (
"fmt"
"math/big"
"sort"
)
type Ledger struct {
Transactions []Transaction
}
func (l *Ledger) ToString() string {
balance := make(map[string]*big.Rat)
for _, t := range l.Transactions {
err := t.CheckBalance()
check(err)
for _, a := range t.Accounts {
if b, ok := balance[a.Name]; ok {
if a.Debit {
b.Add(b, a.Amount)
} else {
b.Sub(b, a.Amount)
}
} else {
if a.Debit {
balance[a.Name] = a.Amount
} else {
neg := new(big.Rat)
neg.SetInt64(-1)
balance[a.Name] = a.Amount.Mul(a.Amount, neg)
}
}
}
}
keys := make([]string, len(balance))
i := 0
for k := range balance {
keys[i] = k
i++
}
sort.Strings(keys)
padLength := 20
for _, key := range keys {
if len(key) > padLength {
padLength = len(key) + 2
}
}
boom := ""
for _, key := range keys {
extra := ""
if balance[key].Sign() == 1 {
extra = "+"
}
boom += fmt.Sprintf("%s%s%s\n", padRight(key, " ", padLength), extra, balance[key].FloatString(2))
}
return boom
}
func padRight(source, c string, length int) string {
for i := len(source); i < length; i++ {
source += c
}
return source
}
func padLeft(source, c string, length int) string {
for i := len(source); i < length; i++ {
source = c + source
}
return source
}