Skip to content

Commit

Permalink
Bug into object function KEEP (#121)
Browse files Browse the repository at this point in the history
  • Loading branch information
3timeslazy authored and ziflex committed Oct 14, 2018
1 parent 6df08a6 commit 0f3128e
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 14 deletions.
24 changes: 10 additions & 14 deletions pkg/stdlib/objects/keep.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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 resultObj, nil
}
return true
})

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
return resultObj, nil
}
18 changes: 18 additions & 0 deletions pkg/stdlib/objects/keep_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down

0 comments on commit 0f3128e

Please sign in to comment.