summaryrefslogtreecommitdiffstats
path: root/tpl/collections
diff options
context:
space:
mode:
authorBjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com>2019-11-11 18:14:45 +0100
committerBjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com>2019-11-11 18:33:22 +0100
commit90d0cdf236b54000bfe444ba3a00236faaa28790 (patch)
tree2cf63ccfd6a250f4b1b7420cd78eec69c0d591ca /tpl/collections
parent95ef93be667afb480184175a319584fd651abf03 (diff)
tpl/collections: Add collections.Reverse
Fixes #6499
Diffstat (limited to 'tpl/collections')
-rw-r--r--tpl/collections/collections.go23
-rw-r--r--tpl/collections/collections_test.go19
2 files changed, 42 insertions, 0 deletions
diff --git a/tpl/collections/collections.go b/tpl/collections/collections.go
index df8aaa6c7..0f0fd7ffb 100644
--- a/tpl/collections/collections.go
+++ b/tpl/collections/collections.go
@@ -417,6 +417,29 @@ func (ns *Namespace) Querify(params ...interface{}) (string, error) {
return qs.Encode(), nil
}
+// Reverse creates a copy of slice and reverses it.
+func (ns *Namespace) Reverse(slice interface{}) (interface{}, error) {
+ if slice == nil {
+ return nil, nil
+ }
+ v := reflect.ValueOf(slice)
+
+ switch v.Kind() {
+ case reflect.Slice:
+ default:
+ return nil, errors.New("argument must be a slice")
+ }
+
+ sliceCopy := reflect.MakeSlice(v.Type(), v.Len(), v.Len())
+
+ for i := v.Len() - 1; i >= 0; i-- {
+ element := sliceCopy.Index(i)
+ element.Set(v.Index(v.Len() - 1 - i))
+ }
+
+ return sliceCopy.Interface(), nil
+}
+
// Seq creates a sequence of integers. It's named and used as GNU's seq.
//
// Examples:
diff --git a/tpl/collections/collections_test.go b/tpl/collections/collections_test.go
index 8946da805..3830a7505 100644
--- a/tpl/collections/collections_test.go
+++ b/tpl/collections/collections_test.go
@@ -211,6 +211,25 @@ func TestDictionary(t *testing.T) {
}
}
+func TestReverse(t *testing.T) {
+ t.Parallel()
+ c := qt.New(t)
+ ns := New(&deps.Deps{})
+
+ s := []string{"a", "b", "c"}
+ reversed, err := ns.Reverse(s)
+ c.Assert(err, qt.IsNil)
+ c.Assert(reversed, qt.DeepEquals, []string{"c", "b", "a"}, qt.Commentf(fmt.Sprint(reversed)))
+ c.Assert(s, qt.DeepEquals, []string{"a", "b", "c"})
+
+ reversed, err = ns.Reverse(nil)
+ c.Assert(err, qt.IsNil)
+ c.Assert(reversed, qt.IsNil)
+ _, err = ns.Reverse(43)
+ c.Assert(err, qt.Not(qt.IsNil))
+
+}
+
func TestEchoParam(t *testing.T) {
t.Parallel()
c := qt.New(t)