diff --git a/docs/templatefuncs.md b/docs/templatefuncs.md index 8bf448b..8f85a18 100644 --- a/docs/templatefuncs.md +++ b/docs/templatefuncs.md @@ -188,11 +188,22 @@ adcda `reverse` returns a copy of *list* in reverse order. ```text -{{ list "a" "b" "c" }} +{{ list "a" "b" "c" | reverse }} [c b a] ``` +## `sort` *list* + +`sort` returns *list* sorted in ascending order. +If *list* cannot be sorted, it is simply returned. + +```text +{{ list list "c" "a" "b" | sort }} + +[a b c] +``` + ## `stat` *path* `stat` returns a map representation of executing diff --git a/templatefuncs.go b/templatefuncs.go index a2eec24..e31d970 100644 --- a/templatefuncs.go +++ b/templatefuncs.go @@ -50,6 +50,7 @@ func NewFuncMap() template.FuncMap { "regexpReplaceAll": regexpReplaceAllTemplateFunc, "replaceAll": replaceAllTemplateFunc, "reverse": reverseTemplateFunc, + "sort": sortTemplateFunc, "stat": eachString(statTemplateFunc), "toJSON": toJSONTemplateFunc, "toLower": eachString(strings.ToLower), @@ -179,6 +180,25 @@ func reverseTemplateFunc(list []any) []any { return listcopy } +// sortTemplateFunc is the core implementation of the `sort` template function. +func sortTemplateFunc(list []any) []any { + strCopy := make([]string, len(list)) + for i, v := range list { + strCopy[i] = toStringTemplateFunc(v) + } + slices.Sort(strCopy) + for i, newValue := range strCopy { + for j, v := range list { + strv := toStringTemplateFunc(v) + if strv == newValue { + list[i], list[j] = list[j], list[i] + break + } + } + } + return list +} + // statTemplateFunc is the core implementation of the `stat` template function. func statTemplateFunc(name string) any { switch fileInfo, err := os.Stat(name); { diff --git a/templatefuncs_test.go b/templatefuncs_test.go index 39331fe..08c532b 100644 --- a/templatefuncs_test.go +++ b/templatefuncs_test.go @@ -133,6 +133,10 @@ func TestFuncMap(t *testing.T) { "# b", ), }, + { + template: `{{ quote "a" }}`, + expected: `"a"`, + }, { template: `{{ "abcba" | replaceAll "b" "d" }}`, expected: `adcda`, @@ -141,14 +145,18 @@ func TestFuncMap(t *testing.T) { template: `{{ list "abc" "cba" | replaceAll "b" "d" }}`, expected: "[adc cda]", }, - { - template: `{{ quote "a" }}`, - expected: `"a"`, - }, { template: `{{ list "a" "b" "c" | reverse }}`, expected: "[c b a]", }, + { + template: `{{ list "c" "a" "b" | sort }}`, + expected: "[a b c]", + }, + { + template: `{{ list 0 4 5 1 | sort }}`, + expected: "[0 1 4 5]", + }, { template: `{{ (stat "testdata/file").type }}`, expected: "file",