2018-10-07 23:53:41 +02:00
|
|
|
package objects
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"sort"
|
|
|
|
|
|
|
|
"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-07 23:53:41 +02:00
|
|
|
)
|
|
|
|
|
2018-10-14 19:06:27 +02:00
|
|
|
// Keys returns string array of object's keys
|
|
|
|
// @params obj (Object) - The object whose keys you want to extract
|
|
|
|
// @params sort (Boolean, optional) - If sort is true, then the returned keys will be sorted.
|
|
|
|
// @returns (Array of String) - Array that contains object keys.
|
2018-10-07 23:53:41 +02:00
|
|
|
func Keys(_ context.Context, args ...core.Value) (core.Value, error) {
|
|
|
|
err := core.ValidateArgs(args, 1, 2)
|
|
|
|
if err != nil {
|
|
|
|
return values.None, err
|
|
|
|
}
|
|
|
|
|
2019-02-13 19:31:18 +02:00
|
|
|
err = core.ValidateType(args[0], types.Object)
|
2018-10-07 23:53:41 +02:00
|
|
|
if err != nil {
|
|
|
|
return values.None, err
|
|
|
|
}
|
|
|
|
|
|
|
|
obj := args[0].(*values.Object)
|
|
|
|
needSort := false
|
|
|
|
|
|
|
|
if len(args) == 2 {
|
2019-02-13 19:31:18 +02:00
|
|
|
err = core.ValidateType(args[1], types.Boolean)
|
2018-10-07 23:53:41 +02:00
|
|
|
if err != nil {
|
|
|
|
return values.None, err
|
|
|
|
}
|
|
|
|
|
|
|
|
needSort = bool(args[1].(values.Boolean))
|
|
|
|
}
|
|
|
|
|
|
|
|
keys := sort.StringSlice(obj.Keys())
|
|
|
|
keysArray := values.NewArray(len(keys))
|
|
|
|
|
|
|
|
if needSort {
|
|
|
|
keys.Sort()
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, key := range keys {
|
|
|
|
keysArray.Push(values.NewString(key))
|
|
|
|
}
|
|
|
|
|
|
|
|
return keysArray, nil
|
|
|
|
}
|