2018-10-09 22:13:00 +02:00
|
|
|
package objects
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
|
|
|
|
"github.com/MontFerret/ferret/pkg/runtime/core"
|
|
|
|
"github.com/MontFerret/ferret/pkg/runtime/values"
|
2019-02-13 19:31:18 +02:00
|
|
|
"github.com/MontFerret/ferret/pkg/runtime/values/types"
|
2018-10-09 22:13:00 +02:00
|
|
|
)
|
|
|
|
|
2019-02-02 04:39:28 +02:00
|
|
|
// KeepKeys returns a new object with only given keys.
|
2018-10-14 19:06:27 +02:00
|
|
|
// @params src (Object) - source object.
|
|
|
|
// @params keys (Array Of String OR Strings) - keys that need to be keeped.
|
|
|
|
// @returns (Object) - New Object with only given keys.
|
2019-02-02 04:39:28 +02:00
|
|
|
func KeepKeys(_ context.Context, args ...core.Value) (core.Value, error) {
|
2018-10-09 22:13:00 +02:00
|
|
|
err := core.ValidateArgs(args, 2, core.MaxArgs)
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return values.None, err
|
|
|
|
}
|
|
|
|
|
2019-02-13 19:31:18 +02:00
|
|
|
err = core.ValidateType(args[0], types.Object)
|
2018-10-09 22:13:00 +02:00
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return values.None, err
|
|
|
|
}
|
|
|
|
|
|
|
|
keys := values.NewArrayWith(args[1:]...)
|
|
|
|
|
2019-02-13 19:31:18 +02:00
|
|
|
if len(args) == 2 && args[1].Type().Equals(types.Array) {
|
2018-10-09 22:13:00 +02:00
|
|
|
keys = args[1].(*values.Array)
|
|
|
|
}
|
|
|
|
|
2019-02-13 19:31:18 +02:00
|
|
|
err = validateArrayOf(types.String, keys)
|
2018-10-09 22:13:00 +02:00
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return values.None, err
|
|
|
|
}
|
|
|
|
|
|
|
|
obj := args[0].(*values.Object)
|
|
|
|
resultObj := values.NewObject()
|
|
|
|
|
|
|
|
var key values.String
|
|
|
|
var val core.Value
|
|
|
|
var exists values.Boolean
|
|
|
|
|
2018-10-14 21:22:41 +02:00
|
|
|
keys.ForEach(func(keyVal core.Value, idx int) bool {
|
|
|
|
key = keyVal.(values.String)
|
|
|
|
|
2018-10-09 22:13:00 +02:00
|
|
|
if val, exists = obj.Get(key); exists {
|
2019-02-13 19:31:18 +02:00
|
|
|
cloneable, ok := val.(core.Cloneable)
|
|
|
|
|
|
|
|
if ok {
|
|
|
|
val = cloneable.Clone()
|
2018-10-14 21:22:41 +02:00
|
|
|
}
|
2019-02-13 19:31:18 +02:00
|
|
|
|
2018-10-09 22:13:00 +02:00
|
|
|
resultObj.Set(key, val)
|
|
|
|
}
|
|
|
|
|
2018-10-14 21:22:41 +02:00
|
|
|
return true
|
|
|
|
})
|
2018-10-09 22:13:00 +02:00
|
|
|
|
2018-10-14 21:22:41 +02:00
|
|
|
return resultObj, nil
|
2018-10-09 22:13:00 +02:00
|
|
|
}
|