1
0
mirror of https://github.com/MontFerret/ferret.git synced 2024-12-25 01:32:13 +02:00
ferret/pkg/stdlib/objects/keep_keys.go

65 lines
1.3 KiB
Go
Raw Normal View History

package objects
import (
"context"
"github.com/MontFerret/ferret/pkg/runtime/core"
"github.com/MontFerret/ferret/pkg/runtime/values"
"github.com/MontFerret/ferret/pkg/runtime/values/types"
)
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) {
err := core.ValidateArgs(args, 2, core.MaxArgs)
if err != nil {
return values.None, err
}
err = core.ValidateType(args[0], types.Object)
if err != nil {
return values.None, err
}
keys := values.NewArrayWith(args[1:]...)
if len(args) == 2 && args[1].Type().Equals(types.Array) {
keys = args[1].(*values.Array)
}
err = validateArrayOf(types.String, keys)
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)
if val, exists = obj.Get(key); exists {
cloneable, ok := val.(core.Cloneable)
if ok {
val = cloneable.Clone()
2018-10-14 21:22:41 +02:00
}
resultObj.Set(key, val)
}
2018-10-14 21:22:41 +02:00
return true
})
2018-10-14 21:22:41 +02:00
return resultObj, nil
}