Added list:add
All checks were successful
Build / build (push) Successful in 1m58s

This commit is contained in:
Leon Mika 2025-01-24 13:25:28 +11:00
parent 258d887182
commit a3b9f399e1
2 changed files with 72 additions and 0 deletions

35
ucl/builtins/lists.go Normal file
View file

@ -0,0 +1,35 @@
package builtins
import (
"context"
"ucl.lmika.dev/ucl"
)
func Lists() ucl.Module {
return ucl.Module{
Name: "lists",
Builtins: map[string]ucl.BuiltinHandler{
"add": listAdd,
},
}
}
func listAdd(ctx context.Context, args ucl.CallArgs) (any, error) {
var target ucl.ModListable
if err := args.Bind(&target); err != nil {
return nil, err
}
for args.NArgs() > 0 {
var obj ucl.Object
if err := args.Bind(&obj); err != nil {
return nil, err
}
if err := target.Insert(-1, obj); err != nil {
return nil, err
}
}
return target, nil
}

View file

@ -0,0 +1,37 @@
package builtins_test
import (
"context"
"github.com/stretchr/testify/assert"
"testing"
"ucl.lmika.dev/ucl"
"ucl.lmika.dev/ucl/builtins"
)
func TestLists_Add(t *testing.T) {
tests := []struct {
desc string
eval string
want any
wantErr bool
}{
{desc: "list add 1", eval: `lists:add [1 2 3] 4`, want: []any{1, 2, 3, 4}},
{desc: "list add 2", eval: `lists:add [1 2 3] 4 5`, want: []any{1, 2, 3, 4, 5}},
{desc: "list add 3", eval: `lists:add [1 2 3]`, want: []any{1, 2, 3}},
}
for _, tt := range tests {
t.Run(tt.desc, func(t *testing.T) {
inst := ucl.New(
ucl.WithModule(builtins.Lists()),
)
res, err := inst.Eval(context.Background(), tt.eval)
if tt.wantErr {
assert.Error(t, err)
} else {
assert.NoError(t, err)
assert.Equal(t, tt.want, res)
}
})
}
}