mirror of
https://github.com/MontFerret/ferret.git
synced 2025-12-01 22:19:32 +02:00
Added objects 'Has' and 'Keys' function (#69)
* add pkg/stdlib/objects Length function * rename lenght.go -> length.go * fix tests according to other tests * add new tests to length tests * delete objects method Length * add objects method Has * add objects function Keys * small fixes in Keys and Has functions * change Has function * unit tests for Keys function
This commit is contained in:
46
pkg/stdlib/objects/keys.go
Normal file
46
pkg/stdlib/objects/keys.go
Normal file
@@ -0,0 +1,46 @@
|
||||
package objects
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sort"
|
||||
|
||||
"github.com/MontFerret/ferret/pkg/runtime/core"
|
||||
"github.com/MontFerret/ferret/pkg/runtime/values"
|
||||
)
|
||||
|
||||
func Keys(_ context.Context, args ...core.Value) (core.Value, error) {
|
||||
err := core.ValidateArgs(args, 1, 2)
|
||||
if err != nil {
|
||||
return values.None, err
|
||||
}
|
||||
|
||||
err = core.ValidateType(args[0], core.ObjectType)
|
||||
if err != nil {
|
||||
return values.None, err
|
||||
}
|
||||
|
||||
obj := args[0].(*values.Object)
|
||||
needSort := false
|
||||
|
||||
if len(args) == 2 {
|
||||
err = core.ValidateType(args[1], core.BooleanType)
|
||||
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
|
||||
}
|
||||
Reference in New Issue
Block a user