diff --git a/docs/Language-Definition.md b/docs/Language-Definition.md index 440c268dd..447726c29 100644 --- a/docs/Language-Definition.md +++ b/docs/Language-Definition.md @@ -148,7 +148,7 @@ user.Age > 30 ? "mature" : "immature" ## Builtin functions -* `len` (length of array or string) +* `len` (length of array, map or string) * `all` (will return `true` if all element satisfies the predicate) * `none` (will return `true` if all element does NOT satisfies the predicate) * `any` (will return `true` if any element satisfies the predicate) diff --git a/expr_test.go b/expr_test.go index 3f04d6c9a..7a9fcb882 100644 --- a/expr_test.go +++ b/expr_test.go @@ -684,6 +684,18 @@ func TestExpr(t *testing.T) { `len(["hello", "world"])`, 2, }, + { + `len("hello, world")`, + 12, + }, + { + `len(Array)`, + 5, + }, + { + `len({a: 1, b: 2, c: 2})`, + 3, + }, { `{foo: 0, bar: 1}`, map[string]interface{}{"foo": 0, "bar": 1}, @@ -696,10 +708,6 @@ func TestExpr(t *testing.T) { `(true ? 0+1 : 2+3) + (false ? -1 : -2)`, -1, }, - { - `len(Array)`, - 5, - }, { `filter(1..9, {# > 7})`, []interface{}{8, 9}, diff --git a/vm/runtime.go b/vm/runtime.go index 9b7f343f9..2dd11ac94 100644 --- a/vm/runtime.go +++ b/vm/runtime.go @@ -173,7 +173,7 @@ func in(needle interface{}, array interface{}) bool { func length(a interface{}) int { v := reflect.ValueOf(a) switch v.Kind() { - case reflect.Array, reflect.Slice, reflect.String: + case reflect.Array, reflect.Slice, reflect.Map, reflect.String: return v.Len() default: panic(fmt.Sprintf("invalid argument for len (type %T)", a))