Skip to content

Commit

Permalink
terrible sort
Browse files Browse the repository at this point in the history
  • Loading branch information
bradenhilton committed May 18, 2024
1 parent 3fd6298 commit b674fe9
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 5 deletions.
13 changes: 12 additions & 1 deletion docs/templatefuncs.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
20 changes: 20 additions & 0 deletions templatefuncs.go
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down Expand Up @@ -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); {
Expand Down
16 changes: 12 additions & 4 deletions templatefuncs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,10 @@ func TestFuncMap(t *testing.T) {
"# b",
),
},
{
template: `{{ quote "a" }}`,
expected: `"a"`,
},
{
template: `{{ "abcba" | replaceAll "b" "d" }}`,
expected: `adcda`,
Expand All @@ -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",
Expand Down

0 comments on commit b674fe9

Please sign in to comment.