Skip to content

Commit

Permalink
perf: remove regexp for calc expr
Browse files Browse the repository at this point in the history
  • Loading branch information
howeyc committed Aug 9, 2023
1 parent 5d0cd97 commit fd6f362
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 12 deletions.
5 changes: 5 additions & 0 deletions decimal/decimal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -320,6 +320,11 @@ var testParseCases = []testCase{
`strconv.ParseInt: parsing "1QZ": invalid syntax`,
"1QZ.56",
},
{
"error-expr-1",
`strconv.ParseInt: parsing "(123 * 6)": invalid syntax`,
"(123 * 6)",
},
}

func TestStringParse(t *testing.T) {
Expand Down
18 changes: 6 additions & 12 deletions parse.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import (
"io"
"os"
"path/filepath"
"regexp"
"strings"
"sync"
"time"
Expand Down Expand Up @@ -80,9 +79,6 @@ func ParseLedgerAsync(ledgerReader io.Reader) (c chan *Transaction, e chan error
return c, e
}

// Calculation expressions are enclosed in parantheses
var calcExpr = regexp.MustCompile(`(?s) \((.*)\)`)

type parser struct {
scanner *bufio.Scanner
filename string
Expand Down Expand Up @@ -238,14 +234,6 @@ func (lp *parser) parseTransaction(dateString, payeeString, payeeComment string)
break
}

// Check for expr
if calcExpr.MatchString(trimmedLine) {
trimmedLine = calcExpr.ReplaceAllStringFunc(trimmedLine, func(s string) string {
f, _ := compute.Evaluate(s)
return fmt.Sprintf("%f", f)
})
}

var accChange Account
accChange.Name = trimmedLine
accChange.Comment = currentComment
Expand All @@ -255,6 +243,12 @@ func (lp *parser) parseTransaction(dateString, payeeString, payeeComment string)
if decbal, derr := decimal.NewFromString(amt); derr == nil {
accChange.Name = acc
accChange.Balance = decbal
} else if i := strings.Index(trimmedLine, "("); i >= 0 {
acc := strings.TrimSpace(trimmedLine[:i])
amt := trimmedLine[i+1 : len(trimmedLine)-1]
f, _ := compute.Evaluate(amt)
accChange.Name = acc
accChange.Balance = decimal.NewFromFloat(f)
}
}
trans.AccountChanges = append(trans.AccountChanges, accChange)
Expand Down

0 comments on commit fd6f362

Please sign in to comment.