diff --git a/cointop/portfolio.go b/cointop/portfolio.go index b01feb8..29ccc3a 100644 --- a/cointop/portfolio.go +++ b/cointop/portfolio.go @@ -12,8 +12,8 @@ import ( "time" "unicode/utf8" - "github.com/Knetic/govaluate" "github.com/miguelmota/cointop/pkg/asciitable" + "github.com/miguelmota/cointop/pkg/eval" "github.com/miguelmota/cointop/pkg/humanize" "github.com/miguelmota/cointop/pkg/pad" "github.com/miguelmota/cointop/pkg/table" @@ -435,22 +435,11 @@ func (ct *Cointop) SetPortfolioHoldings() error { return nil } - var holdings float64 = 0 - input := strings.TrimSpace(string(b[:n])) // remove trailing \0s - if input != "" { - expression, err := govaluate.NewEvaluableExpression(input) - if err != nil { - return nil // invalid expression - don't change anything - } - result, err := expression.Evaluate(nil) - if err != nil { - return nil // could not evaluate - don't change anything - } - var ok bool - holdings, ok = result.(float64) - if !ok { - return nil // not a float64 - don't change anything - } + input := string(b[:n]) + holdings, err := eval.EvaluateExpressionToFloat64(input) + if err != nil { + // leave value as is if expression can't be evaluated + return nil } shouldDelete := holdings == 0 diff --git a/go.mod b/go.mod index 9495c01..790a842 100644 --- a/go.mod +++ b/go.mod @@ -2,7 +2,7 @@ module github.com/miguelmota/cointop require ( github.com/BurntSushi/toml v0.3.1 - github.com/Knetic/govaluate v3.0.0+incompatible // indirect + github.com/Knetic/govaluate v3.0.0+incompatible github.com/acarl005/stripansi v0.0.0-20180116102854-5a71ef0e047d github.com/anaskhan96/soup v1.1.1 // indirect github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be // indirect diff --git a/pkg/eval/eval.go b/pkg/eval/eval.go new file mode 100644 index 0000000..3e51108 --- /dev/null +++ b/pkg/eval/eval.go @@ -0,0 +1,29 @@ +package eval + +import ( + "errors" + "strings" + + "github.com/Knetic/govaluate" +) + +// EvaluateExpression ... +func EvaluateExpressionToFloat64(expressionInput string) (float64, error) { + expressionInput = strings.TrimSpace(expressionInput) // remove trailing \0s + if expressionInput == "" { + return 0, nil + } + expression, err := govaluate.NewEvaluableExpression(expressionInput) + if err != nil { + return 0, err + } + result, err := expression.Evaluate(nil) + if err != nil { + return 0, err + } + f64, ok := result.(float64) + if !ok { + return 0, errors.New("could not type assert float64") + } + return f64, nil +}