Skip to content

Commit

Permalink
Add reverse() function to lists extension.
Browse files Browse the repository at this point in the history
  • Loading branch information
seirl committed Oct 14, 2024
1 parent 26b10bf commit 3214b32
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 0 deletions.
13 changes: 13 additions & 0 deletions ext/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -442,6 +442,19 @@ Examples:
lists.range(5) -> [0, 1, 2, 3, 4]


### Reverse

**Introduced in version 2**

Returns the elements of a list in reverse order.

<list(T)>.reverse() -> <list(T)>

Examples:

[5, 3, 1, 2].reverse() // return [2, 1, 3, 5]


### Slice


Expand Down
34 changes: 34 additions & 0 deletions ext/lists.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,17 @@ var comparableTypes = []*cel.Type{
//
// lists.range(5) -> [0, 1, 2, 3, 4]
//
// # Reverse
//
// Introduced in version: 2
//
// Returns the elements of a list in reverse order.
//
// <list(T)>.reverse() -> <list(T)>
//
// Examples:
//
// [5, 3, 1, 2].reverse() // return [2, 1, 3, 5]
//
// # Slice
//
Expand Down Expand Up @@ -245,6 +256,19 @@ func (lib listsLib) CompileOptions() []cel.EnvOption {
}),
),
))
opts = append(opts, cel.Function("reverse",
cel.MemberOverload("list_reverse",
[]*cel.Type{listType}, listType,
cel.FunctionBinding(func(args ...ref.Val) ref.Val {
list := args[0].(traits.Lister)
result, err := reverseList(list)
if err != nil {
return types.WrapErr(err)
}
return result
}),
),
))
}

return opts
Expand All @@ -263,6 +287,16 @@ func genRange(n types.Int) (ref.Val, error) {
return types.DefaultTypeAdapter.NativeToValue(newList), nil
}

func reverseList(list traits.Lister) (ref.Val, error) {
var newList []ref.Val
listLength := list.Size().(types.Int)
for i := types.Int(0); i < listLength; i++ {
val := list.Get(listLength - i - 1)
newList = append(newList, val)
}
return types.DefaultTypeAdapter.NativeToValue(newList), nil
}

func slice(list traits.Lister, start, end types.Int) (ref.Val, error) {
listLength := list.Size().(types.Int)
if start < 0 || end < 0 {
Expand Down
1 change: 1 addition & 0 deletions ext/lists_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ func TestLists(t *testing.T) {
{expr: `[1,2,3,4].slice(0, 10)`, err: "cannot slice(0, 10), list is length 4"},
{expr: `[1,2,3,4].slice(-5, 10)`, err: "cannot slice(-5, 10), negative indexes not supported"},
{expr: `[1,2,3,4].slice(-5, -3)`, err: "cannot slice(-5, -3), negative indexes not supported"},

{expr: `dyn([]).flatten() == []`},
{expr: `dyn([1,2,3,4]).flatten() == [1,2,3,4]`},
{expr: `[1,[2,[3,4]]].flatten() == [1,2,[3,4]]`},
Expand Down

0 comments on commit 3214b32

Please sign in to comment.