impl NewBPIs(path)[currency].Get(date)
This commit is contained in:
@@ -3,24 +3,17 @@ package ledger
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
type BPIs string
|
||||
type BPIs map[Currency]BPI
|
||||
|
||||
type BPI map[string]float64
|
||||
|
||||
func NewBPIs(p string) (BPIs, error) {
|
||||
bpis := BPIs(p)
|
||||
_, err := bpis.values()
|
||||
return bpis, err
|
||||
}
|
||||
|
||||
func (bpis BPIs) values() (map[Currency]BPI, error) {
|
||||
f, err := os.Open(string(bpis))
|
||||
f, err := os.Open(p)
|
||||
if os.IsNotExist(err) {
|
||||
return nil, nil
|
||||
}
|
||||
@@ -37,15 +30,17 @@ func (bpis BPIs) values() (map[Currency]BPI, error) {
|
||||
if len(line) > 0 {
|
||||
fields := bytes.Fields(line)
|
||||
if len(fields) > 3 {
|
||||
date := fields[1]
|
||||
currency := fields[len(fields)-2]
|
||||
date := string(fields[1])
|
||||
currency := Currency(fields[len(fields)-2])
|
||||
value, err := strconv.ParseFloat(string(fields[len(fields)-1][1:]), 64)
|
||||
if err != nil {
|
||||
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 {
|
||||
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]
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user