Skip to content

Commit

Permalink
perf: only compile regex once
Browse files Browse the repository at this point in the history
  • Loading branch information
ascandone committed Nov 12, 2024
1 parent 08f979a commit e27150c
Showing 1 changed file with 5 additions and 4 deletions.
9 changes: 5 additions & 4 deletions internal/interpreter/interpreter.go
Original file line number Diff line number Diff line change
Expand Up @@ -858,15 +858,17 @@ func (st *programState) evaluateSentAmt(sentValue parser.SentValue) (*string, *b
}
}

var percentRegex = regexp.MustCompile(`^([0-9]+)(?:[.]([0-9]+))?[%]$`)
var fractionRegex = regexp.MustCompile(`^([0-9]+)\s?[/]\s?([0-9]+)$`)

// slightly edited copy-paste from:
// https://github.com/formancehq/ledger/blob/b188d0c80eadaab5024d74edc967c7005e155f7c/internal/machine/portion.go#L57

func ParsePortionSpecific(input string) (*big.Rat, InterpreterError) {
var res *big.Rat
var ok bool

re := regexp.MustCompile(`^([0-9]+)(?:[.]([0-9]+))?[%]$`)
percentMatch := re.FindStringSubmatch(input)
percentMatch := percentRegex.FindStringSubmatch(input)
if len(percentMatch) != 0 {
integral := percentMatch[1]
fractional := percentMatch[2]
Expand All @@ -876,8 +878,7 @@ func ParsePortionSpecific(input string) (*big.Rat, InterpreterError) {
}

Check warning on line 878 in internal/interpreter/interpreter.go

View check run for this annotation

Codecov / codecov/patch

internal/interpreter/interpreter.go#L877-L878

Added lines #L877 - L878 were not covered by tests
res.Mul(res, big.NewRat(1, 100))
} else {
re = regexp.MustCompile(`^([0-9]+)\s?[/]\s?([0-9]+)$`)
fractionMatch := re.FindStringSubmatch(input)
fractionMatch := fractionRegex.FindStringSubmatch(input)
if len(fractionMatch) != 0 {
numerator := fractionMatch[1]
denominator := fractionMatch[2]
Expand Down

0 comments on commit e27150c

Please sign in to comment.