Skip to content

Commit

Permalink
Array length
Browse files Browse the repository at this point in the history
  • Loading branch information
zix99 committed Jun 4, 2024
1 parent c46fe54 commit aff0c32
Show file tree
Hide file tree
Showing 4 changed files with 33 additions and 0 deletions.
8 changes: 8 additions & 0 deletions docs/usage/expressions.md
Original file line number Diff line number Diff line change
Expand Up @@ -324,6 +324,14 @@ Syntax: `{@ ele0 ele1 ele2}` (`{$ ele0 ele1 ele2}` is equivalent)

Creates an array with the provided elements. Use `{@}` for an array of all matches.

#### @len

Syntax: `{@len array}`

Returns the length of an array. Empty "" returns 0, a literal will be 1.

**Note:** This is a linear-time operation.

#### @in

Syntax: `{@in <val> array}` or `{@in <val> {@ val0 val1 val2 ...}}`
Expand Down
1 change: 1 addition & 0 deletions pkg/expressions/stdlib/funcs.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ var StandardFunctions = map[string]KeyBuilderFunction{

// Ranges
"@": kfJoin(ArraySeparator),
"@len": kfArrayLen,
"@map": kfArrayMap,
"@split": kfArraySplit,
"@select": kfArraySelect,
Expand Down
17 changes: 17 additions & 0 deletions pkg/expressions/stdlib/funcsRange.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
. "rare/pkg/expressions" //lint:ignore ST1001 Legacy
"rare/pkg/slicepool"
"rare/pkg/stringSplitter"
"strconv"
"strings"
)

Expand Down Expand Up @@ -34,6 +35,22 @@ func (s *subContext) Eval(stage KeyBuilderStage, v0, v1 string) string {
return stage(s)
}

// {@len <arr>}
func kfArrayLen(args []KeyBuilderStage) (KeyBuilderStage, error) {
if len(args) != 1 {
return stageErrArgCount(args, 1)
}
return func(context KeyBuilderContext) string {
val := args[0](context)
if val == "" {
return "0"
}

count := strings.Count(val, ArraySeparatorString) + 1
return strconv.Itoa(count)
}, nil
}

// {@split <string> "delim"}
func kfArraySplit(args []KeyBuilderStage) (KeyBuilderStage, error) {
if !isArgCountBetween(args, 1, 2) {
Expand Down
7 changes: 7 additions & 0 deletions pkg/expressions/stdlib/funcsRange_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,13 @@ func TestArray(t *testing.T) {
testExpression(t, mockContext("q"), "{$ {0}}", "q")
}

func TestArrayLen(t *testing.T) {
testExpression(t, mockContext("abc"), "{@len {0}}", "1")
testExpression(t, mockContext(expressions.MakeArray("a", "bc", "c")), "{@len {0}}", "3")
testExpression(t, mockContext(""), "{@len {0}}", "0")
testExpressionErr(t, mockContext(), "{@len a b}", "<ARGN>", ErrArgCount)
}

func TestArraySplit(t *testing.T) {
testExpression(
t,
Expand Down

0 comments on commit aff0c32

Please sign in to comment.