Skip to content

Commit e8bd7f8

Browse files
committed
Make len() return runes count for string
Fixes #746
1 parent 79b1170 commit e8bd7f8

File tree

2 files changed

+16
-1
lines changed

2 files changed

+16
-1
lines changed

builtin/lib.go

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,15 +5,18 @@ import (
55
"math"
66
"reflect"
77
"strconv"
8+
"unicode/utf8"
89

910
"github.com/expr-lang/expr/internal/deref"
1011
)
1112

1213
func Len(x any) any {
1314
v := reflect.ValueOf(x)
1415
switch v.Kind() {
15-
case reflect.Array, reflect.Slice, reflect.Map, reflect.String:
16+
case reflect.Array, reflect.Slice, reflect.Map:
1617
return v.Len()
18+
case reflect.String:
19+
return utf8.RuneCountInString(v.String())
1720
default:
1821
panic(fmt.Sprintf("invalid argument for len (type %T)", x))
1922
}

expr_test.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -871,6 +871,18 @@ func TestExpr(t *testing.T) {
871871
`len("hello, world")`,
872872
12,
873873
},
874+
{
875+
`len('北京')`,
876+
2,
877+
},
878+
{
879+
`len('👍🏻')`, // one grapheme cluster, two code points
880+
2,
881+
},
882+
{
883+
`len('👍')`, // one grapheme cluster, one code point
884+
1,
885+
},
874886
{
875887
`len(ArrayOfInt)`,
876888
5,

0 commit comments

Comments
 (0)