impl NewBPIs(path)[currency].Get(date)

main
Bel LaPointe 2023-10-25 13:44:46 -06:00
parent 4a4bcf3302
commit f2ec1233d7
2 changed files with 33 additions and 13 deletions

View File

@ -3,24 +3,17 @@ package ledger
import ( import (
"bufio" "bufio"
"bytes" "bytes"
"fmt"
"io" "io"
"os" "os"
"strconv" "strconv"
) )
type BPIs string type BPIs map[Currency]BPI
type BPI map[string]float64 type BPI map[string]float64
func NewBPIs(p string) (BPIs, error) { func NewBPIs(p string) (BPIs, error) {
bpis := BPIs(p) f, err := os.Open(p)
_, err := bpis.values()
return bpis, err
}
func (bpis BPIs) values() (map[Currency]BPI, error) {
f, err := os.Open(string(bpis))
if os.IsNotExist(err) { if os.IsNotExist(err) {
return nil, nil return nil, nil
} }
@ -37,15 +30,17 @@ func (bpis BPIs) values() (map[Currency]BPI, error) {
if len(line) > 0 { if len(line) > 0 {
fields := bytes.Fields(line) fields := bytes.Fields(line)
if len(fields) > 3 { if len(fields) > 3 {
date := fields[1] date := string(fields[1])
currency := fields[len(fields)-2] currency := Currency(fields[len(fields)-2])
value, err := strconv.ParseFloat(string(fields[len(fields)-1][1:]), 64) value, err := strconv.ParseFloat(string(fields[len(fields)-1][1:]), 64)
if err != nil { if err != nil {
return nil, err return nil, err
} }
return nil, fmt.Errorf("what do with %s/%s/%.2f?", date, currency, value) if _, ok := result[currency]; !ok {
result[currency] = make(BPI)
}
result[currency][date] = value
} }
return nil, fmt.Errorf("what do: %s", line)
} }
if err == io.EOF { if err == io.EOF {
return result, nil return result, nil
@ -54,3 +49,16 @@ func (bpis BPIs) values() (map[Currency]BPI, error) {
} }
} }
} }
func (bpi BPI) Lookup(date string) float64 {
var closestWithoutGoingOver string
for k := range bpi {
if k <= date && k > closestWithoutGoingOver {
closestWithoutGoingOver = k
}
}
if closestWithoutGoingOver == "" {
return 0
}
return bpi[closestWithoutGoingOver]
}

View File

@ -157,5 +157,17 @@ P 2023-10-22 07:33:56 GME $17.18
t.Fatal(err) t.Fatal(err)
} }
if got := got["USDC"].Lookup("2099-01-01"); got != 0 {
t.Error("default got != 0:", got)
}
if got := got["GME"].Lookup("2099-01-01"); got != 17.18 {
t.Errorf("shouldve returned latest but got %v", got)
}
if got := got["GME"].Lookup("2023-09-19"); got != 18.22 {
t.Errorf("shouldve returned one day before but got %v", got)
}
if got := got["GME"].Lookup("2023-09-18"); got != 18.22 {
t.Errorf("shouldve returned day of but got %v", got)
}
t.Log(got) t.Log(got)
} }