diff --git a/pkg/stdlib/objects/keep.go b/pkg/stdlib/objects/keep.go index 45e3734c..88f6e8ca 100644 --- a/pkg/stdlib/objects/keep.go +++ b/pkg/stdlib/objects/keep.go @@ -30,7 +30,7 @@ func Keep(_ context.Context, args ...core.Value) (core.Value, error) { keys = args[1].(*values.Array) } - err = validateArrayOfStrings(keys) + err = validateArrayOf(core.StringType, keys) if err != nil { return values.None, err @@ -43,22 +43,18 @@ func Keep(_ context.Context, args ...core.Value) (core.Value, error) { var val core.Value var exists values.Boolean - for idx := values.NewInt(0); idx < keys.Length(); idx++ { - key = keys.Get(idx).(values.String) + keys.ForEach(func(keyVal core.Value, idx int) bool { + key = keyVal.(values.String) + if val, exists = obj.Get(key); exists { + if values.IsCloneable(val) { + val = val.(core.Cloneable).Clone() + } resultObj.Set(key, val) } - } + + return true + }) return resultObj, nil } - -func validateArrayOfStrings(arr *values.Array) (err error) { - for idx := values.NewInt(0); idx < arr.Length(); idx++ { - err = core.ValidateType(arr.Get(idx), core.StringType) - if err != nil { - break - } - } - return -} diff --git a/pkg/stdlib/objects/keep_test.go b/pkg/stdlib/objects/keep_test.go index d3718643..03ea8e88 100644 --- a/pkg/stdlib/objects/keep_test.go +++ b/pkg/stdlib/objects/keep_test.go @@ -45,6 +45,24 @@ func TestKeep(t *testing.T) { So(err, ShouldBeError) So(obj, ShouldEqual, values.None) }) + + Convey("Result object is independent of the source object", t, func() { + arr := values.NewArrayWith(values.Int(0)) + obj := values.NewObjectWith( + values.NewObjectProperty("a", arr), + ) + resultObj := values.NewObjectWith( + values.NewObjectProperty("a", values.NewArrayWith(values.Int(0))), + ) + + afterKeep, err := objects.Keep(context.Background(), obj, values.NewString("a")) + + So(err, ShouldBeNil) + + arr.Push(values.NewInt(1)) + + So(afterKeep.Compare(resultObj), ShouldEqual, 0) + }) } func TestKeepStrings(t *testing.T) {