From 7b11e14ff07a21aae9497442501c6ea93fdaf134 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gerry=20Wei=C3=9Fbach?= Date: Wed, 16 Jun 2021 08:13:35 +0200 Subject: [PATCH 1/2] Add sorting, reverse and reverse sorting of objects --- template.go | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/template.go b/template.go index 259a8f88..f21d7a1b 100644 --- a/template.go +++ b/template.go @@ -14,6 +14,7 @@ import ( "path/filepath" "reflect" "regexp" + "sort" "strconv" "strings" "syscall" @@ -428,6 +429,36 @@ func when(condition bool, trueValue, falseValue interface{}) interface{} { } } +// sortStrings returns a sorted array of strings +func sortStrings(values []string) []string { + sort.Strings(values) + return values +} + +// sortStrings returns a sorted array of strings +func sortStringsReverse(values []string) []string { + sort.Sort(sort.Reverse(sort.StringSlice( values ))) + return values +} + +// sortObjects returns a sorted array of objects (sorted by object key field) +func sortObjects(objs interface{}, key string) (interface{}, error) { + objsVal, err := getArrayValues("sortObj", objs) + if err != nil { + return nil, err + } + data := make([]interface{}, objsVal.Len()) + for i := 0; i < objsVal.Len(); i++ { + data[i] = objsVal.Index(i).Interface() + } + sort.Slice(data, func(i, j int) bool { + a := reflect.ValueOf(deepGet(data[i], key)).Interface().(string) + b := reflect.ValueOf(deepGet(data[j], key)).Interface().(string) + return a < b + }) + return data, nil +} + func newTemplate(name string) *template.Template { tmpl := template.New(name).Funcs(template.FuncMap{ "closest": arrayClosest, @@ -451,9 +482,13 @@ func newTemplate(name string) *template.Template { "parseBool": strconv.ParseBool, "parseJson": unmarshalJson, "queryEscape": url.QueryEscape, + "reverse": sort.Reverse, "sha1": hashSha1, "split": strings.Split, "splitN": strings.SplitN, + "sortStrings": sortStrings, + "sortStringsReverse": sortStringsReverse, + "sortObjects": sortObjects, "trimPrefix": trimPrefix, "trimSuffix": trimSuffix, "trim": trim, From e888f9d2630b16e3457a4d5c852bda3bae7a524f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gerry=20Wei=C3=9Fbach?= Date: Wed, 16 Jun 2021 08:15:56 +0200 Subject: [PATCH 2/2] Code Format --- template.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/template.go b/template.go index f21d7a1b..e2245209 100644 --- a/template.go +++ b/template.go @@ -437,7 +437,7 @@ func sortStrings(values []string) []string { // sortStrings returns a sorted array of strings func sortStringsReverse(values []string) []string { - sort.Sort(sort.Reverse(sort.StringSlice( values ))) + sort.Sort(sort.Reverse(sort.StringSlice(values))) return values }