Skip to content

Commit

Permalink
topdown: Added a new array reverse function
Browse files Browse the repository at this point in the history
ast: Updated the builtins list

partially fixes open-policy-agent#3736

Signed-off-by: Olamide Omolola <omololaolamidex@gmail.com>
  • Loading branch information
olamiko committed Nov 5, 2021
1 parent a985df9 commit 91e2822
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
11 changes: 11 additions & 0 deletions ast/builtins.go
Expand Up @@ -80,6 +80,7 @@ var DefaultBuiltins = [...]*Builtin{
// Arrays
ArrayConcat,
ArraySlice,
ArrayReverse,

// Conversions
ToNumber,
Expand Down Expand Up @@ -711,6 +712,16 @@ var ArraySlice = &Builtin{
),
}

var ArrayReverse = &Builtin{
Name: "array.reverse",
Decl: types.NewFunction(
types.Args(
types.NewArray(nil, types.A),
),
types.NewArray(nil, types.A),
),
}

/**
* Conversions
*/
Expand Down
20 changes: 20 additions & 0 deletions topdown/array.go
Expand Up @@ -71,7 +71,27 @@ func builtinArraySlice(a, i, j ast.Value) (ast.Value, error) {
return arr.Slice(startIndex, stopIndex), nil
}

func builtinArrayReverse(bctx BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error {
arr, err := builtins.ArrayOperand(operands[0].Value, 1)
if err != nil {
return err
}

length := arr.Len()
reversedArr := make([]*ast.Term, length)
index := 0

for index < length {
reversedArr[index] = arr.Elem(length - index - 1) //
index++
}

return iter(ast.ArrayTerm(reversedArr...))

}

func init() {
RegisterFunctionalBuiltin2(ast.ArrayConcat.Name, builtinArrayConcat)
RegisterFunctionalBuiltin3(ast.ArraySlice.Name, builtinArraySlice)
RegisterBuiltinFunc(ast.ArrayReverse.Name, builtinArrayReverse)
}

0 comments on commit 91e2822

Please sign in to comment.