From 64feef8b955842c8f0b92c694b64f028ea024a1e Mon Sep 17 00:00:00 2001 From: Pierre-Olivier Mercier Date: Sun, 21 Aug 2022 21:29:22 +0200 Subject: [PATCH] libfic: New function to analyze number flag --- libfic/flag_key.go | 38 ++++++++++++++++++++++++++++++++++++++ libfic/team_my.go | 33 ++++----------------------------- 2 files changed, 42 insertions(+), 29 deletions(-) diff --git a/libfic/flag_key.go b/libfic/flag_key.go index 98c50ed5..5c735c19 100644 --- a/libfic/flag_key.go +++ b/libfic/flag_key.go @@ -6,6 +6,7 @@ import ( "fmt" "regexp" "sort" + "strconv" "strings" "time" @@ -47,6 +48,43 @@ type FlagKey struct { BonusGain int32 `json:"bonus_gain"` } +func AnalyzeNumberFlag(t string) (min, max, step *float64, err error) { + fields := strings.Split(t, ",") + + if len(fields) != 4 || fields[0] != "number" { + err = errors.New("this is not a flag of type 'number'") + return + } + + if len(fields[1]) > 0 { + min = new(float64) + *min, err = strconv.ParseFloat(fields[1], 64) + if err != nil { + return + } + } + + if len(fields[2]) > 0 { + max = new(float64) + *max, err = strconv.ParseFloat(fields[2], 64) + if err != nil { + return + } + } + + if len(fields[3]) > 0 { + step = new(float64) + *step, err = strconv.ParseFloat(fields[3], 64) + if err != nil { + return + } + } else { + *step = 1 + } + + return +} + // GetFlagKeys returns a list of key's flags comming with the challenge. func (e *Exercice) GetFlagKeys() ([]*FlagKey, error) { if rows, err := DBQuery("SELECT id_flag, id_exercice, ordre, label, type, placeholder, help, unit, ignorecase, notrim, multiline, validator_regexp, sort_re_grps, cksum, choices_cost, bonus_gain FROM exercice_flags WHERE id_exercice = ?", e.Id); err != nil { diff --git a/libfic/team_my.go b/libfic/team_my.go index b16fc4f1..72cc26f1 100644 --- a/libfic/team_my.go +++ b/libfic/team_my.go @@ -236,35 +236,10 @@ func MyJSONTeam(t *Team, started bool) (interface{}, error) { } if strings.HasPrefix(flag.Type, "number") { - fields := strings.Split(flag.Type, ",") - if len(fields) == 4 { - flag.Type = fields[0] - - var tmp_min, tmp_max, tmp_step float64 - - if len(fields[1]) > 0 { - tmp_min, err = strconv.ParseFloat(fields[1], 64) - if err != nil { - return nil, err - } - flag.Min = &tmp_min - } - - if len(fields[2]) > 0 { - tmp_max, err = strconv.ParseFloat(fields[2], 64) - if err != nil { - return nil, err - } - flag.Max = &tmp_max - } - - if len(fields[3]) > 0 { - tmp_step, err = strconv.ParseFloat(fields[3], 64) - if err != nil { - return nil, err - } - flag.Step = &tmp_step - } + flag.Type = "number" + flag.Min, flag.Max, flag.Step, err = AnalyzeNumberFlag(flag.Type) + if err != nil { + return nil, err } }