fixed panic when using mutators on floats

This commit is contained in:
Timon Ringwald
2022-04-18 20:39:41 +02:00
parent d733246517
commit f66d9d7f3b
2 changed files with 50 additions and 4 deletions

34
main.go
View File

@ -6,6 +6,7 @@ import (
"fmt"
"io"
"os"
"reflect"
"regexp"
"strconv"
"strings"
@ -164,14 +165,13 @@ func numMut2func[T int64 | float64](mutation string) (f func(value T, vars []str
mutators = append(mutators, mut)
}
numberParser := number_parser[T]()
return func(value T, vars []string) T {
for _, mutator := range mutators {
var otherValue T
if mutator.Var {
other, err := strconv.Atoi(vars[mutator.Value])
if err != nil {
panic("back reference group for number mutator is not a number")
}
other := numberParser(vars[mutator.Value])
otherValue = T(other)
} else {
otherValue = T(mutator.Value)
@ -193,3 +193,29 @@ func numMut2func[T int64 | float64](mutation string) (f func(value T, vars []str
return value
}
}
func number_parser[T int64 | float64]() func(str string) T {
typeOfT := reflect.TypeOf(new(T)).Elem()
typeOfInt64 := reflect.TypeOf(new(int64)).Elem()
typeOfFloat64 := reflect.TypeOf(new(float64)).Elem()
if typeOfT == typeOfInt64 {
return func(str string) T {
num, err := strconv.Atoi(str)
if err != nil {
panic("expected integer but found " + str)
}
return T(num)
}
} else if typeOfT == typeOfFloat64 {
return func(str string) T {
num, err := strconv.ParseFloat(str, 64)
if err != nil {
panic("expected float but found " + str)
}
return T(num)
}
}
panic("invalid number type")
}