Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion pkg/jp/functions/at.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package functions

import (
"errors"
"fmt"
)

func jpfAt(arguments []any) (any, error) {
Expand All @@ -10,6 +11,10 @@ func jpfAt(arguments []any) (any, error) {
} else if index, ok := arguments[1].(float64); !ok {
return nil, errors.New("invalid type, second argument must be an int")
} else {
return slice[int(index)], nil
i := int(index)
if i < 0 || i >= len(slice) {
return nil, fmt.Errorf("index out of range: %d (array length %d)", i, len(slice))
}
return slice[i], nil
}
}
47 changes: 47 additions & 0 deletions pkg/jp/functions/at_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package functions

import (
"testing"
)

func Test_jpfAt(t *testing.T) {
tests := []struct {
name string
args []any
want any
wantErr bool
}{{
name: "valid index",
args: []any{[]any{"a", "b"}, float64(1)},
want: "b",
}, {
name: "first element",
args: []any{[]any{"a", "b"}, float64(0)},
want: "a",
}, {
name: "out of range",
args: []any{[]any{"a", "b"}, float64(999)},
wantErr: true,
}, {
name: "negative index",
args: []any{[]any{"a", "b"}, float64(-1)},
wantErr: true,
}}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := jpfAt(tt.args)
if (err != nil) != tt.wantErr {
t.Fatalf("jpfAt() error = %v, wantErr %v", err, tt.wantErr)
}
if tt.wantErr {
if got != nil {
t.Fatalf("jpfAt() returned a value %v on error, want nil", got)
}
return
}
if got != tt.want {
t.Fatalf("jpfAt() = %v, want %v", got, tt.want)
}
})
}
}