From 9ca3d5925361206fbf061681e55afa9a4d64d584 Mon Sep 17 00:00:00 2001 From: SimFG Date: Thu, 19 Sep 2024 14:34:22 +0800 Subject: [PATCH] add `mapValue` function to get the map value --- builtin/builtin.go | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/builtin/builtin.go b/builtin/builtin.go index e75f9544..b8465cae 100644 --- a/builtin/builtin.go +++ b/builtin/builtin.go @@ -732,6 +732,37 @@ var Builtins = []*Function{ return anyType, fmt.Errorf("cannot get values from %s", args[0]) }, }, + { + Name: "mapValue", + Func: func(args ...any) (any, error) { + if len(args) != 2 { + return nil, fmt.Errorf("invalid number of arguments (expected 2, got %d)", len(args)) + } + v := reflect.ValueOf(args[0]) + if v.Kind() != reflect.Map { + return nil, fmt.Errorf("cannot get values from %s", v.Kind()) + } + keys := v.MapKeys() + for _, key := range keys { + if key.Interface() == args[1] { + return v.MapIndex(key).Interface(), nil + } + } + return nil, nil + }, + Validate: func(args []reflect.Type) (reflect.Type, error) { + if len(args) != 2 { + return anyType, fmt.Errorf("invalid number of arguments (expected 2, got %d)", len(args)) + } + switch kind(args[0]) { + case reflect.Interface: + return arrayType, nil + case reflect.Map: + return arrayType, nil + } + return anyType, fmt.Errorf("cannot get values from %s", args[0]) + }, + }, { Name: "toPairs", Func: func(args ...any) (any, error) {