Skip to content
This repository was archived by the owner on Dec 16, 2025. It is now read-only.

Commit 0074ecf

Browse files
committed
Patch expression to substitute Float64 for Integer. Update docs to include '/'
1 parent 9e41452 commit 0074ecf

2 files changed

Lines changed: 20 additions & 8 deletions

File tree

docs/content/faq.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -165,7 +165,7 @@ draft: false
165165

166166
Press <kbd>e</kbd> on the highlighted coin to enter holdings and add to your portfolio.
167167

168-
This dialog supports basic expressions including `+` `-` `*` etc.
168+
This dialog supports basic expressions including `+` `-` `*` `/` etc.
169169

170170
## How do I edit the holdings of a coin in my portfolio?
171171

pkg/eval/eval.go

Lines changed: 19 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,25 +5,37 @@ import (
55
"strings"
66

77
"github.com/antonmedv/expr"
8+
"github.com/antonmedv/expr/ast"
89
)
910

11+
// AST Visitor that changes Integer to Float
12+
type patcher struct{}
13+
14+
func (p *patcher) Enter(_ *ast.Node) {}
15+
func (p *patcher) Exit(node *ast.Node) {
16+
n, ok := (*node).(*ast.IntegerNode)
17+
if ok {
18+
ast.Patch(node, &ast.FloatNode{Value: float64(n.Value)})
19+
}
20+
}
21+
1022
// EvaluateExpression evaulates a simple math expression string to a float64
1123
func EvaluateExpressionToFloat64(input string) (float64, error) {
12-
input = strings.TrimSpace(input) // remove trailing \0s
24+
input = strings.TrimSpace(input)
1325
if input == "" {
1426
return 0, nil
1527
}
16-
result, err := expr.Eval(input, nil)
28+
program, err := expr.Compile(input, expr.Env(nil), expr.Patch(&patcher{}))
29+
if err != nil {
30+
return 0, err
31+
}
32+
result, err := expr.Run(program, nil)
1733
if err != nil {
1834
return 0, err
1935
}
2036
f64, ok := result.(float64)
2137
if !ok {
22-
ival, ok := result.(int)
23-
if !ok {
24-
return 0, errors.New("could not type assert float64")
25-
}
26-
f64 = float64(ival)
38+
return 0, errors.New("could not type assert float64")
2739
}
2840
return f64, nil
2941
}

0 commit comments

Comments
 (0)