github.com/MontFerret/ferret@v0.18.0/pkg/stdlib/objects/keys.go (about)

     1  package objects
     2  
     3  import (
     4  	"context"
     5  	"sort"
     6  
     7  	"github.com/MontFerret/ferret/pkg/runtime/core"
     8  	"github.com/MontFerret/ferret/pkg/runtime/values"
     9  	"github.com/MontFerret/ferret/pkg/runtime/values/types"
    10  )
    11  
    12  // KEYS returns string array of object's keys
    13  // @param {Object} obj - The object whose keys you want to extract
    14  // @param {Boolean} [sort=False] - If sort is true, then the returned keys will be sorted.
    15  // @return {String[]} - Array that contains object keys.
    16  func Keys(_ context.Context, args ...core.Value) (core.Value, error) {
    17  	err := core.ValidateArgs(args, 1, 2)
    18  	if err != nil {
    19  		return values.None, err
    20  	}
    21  
    22  	err = core.ValidateType(args[0], types.Object)
    23  	if err != nil {
    24  		return values.None, err
    25  	}
    26  
    27  	obj := args[0].(*values.Object)
    28  	needSort := false
    29  
    30  	if len(args) == 2 {
    31  		err = core.ValidateType(args[1], types.Boolean)
    32  		if err != nil {
    33  			return values.None, err
    34  		}
    35  
    36  		needSort = bool(args[1].(values.Boolean))
    37  	}
    38  
    39  	oKeys := make([]string, 0, obj.Length())
    40  
    41  	obj.ForEach(func(value core.Value, key string) bool {
    42  		oKeys = append(oKeys, key)
    43  
    44  		return true
    45  	})
    46  
    47  	keys := sort.StringSlice(oKeys)
    48  	keysArray := values.NewArray(len(keys))
    49  
    50  	if needSort {
    51  		keys.Sort()
    52  	}
    53  
    54  	for _, key := range keys {
    55  		keysArray.Push(values.NewString(key))
    56  	}
    57  
    58  	return keysArray, nil
    59  }