Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a virtual method "length" on slices, arrays, strings to match JS engines #26

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions eval.go
Original file line number Diff line number Diff line change
Expand Up @@ -364,6 +364,14 @@ func (v *evalVisitor) evalMethod(ctx reflect.Value, name string, exprRoot bool)
}

if !method.IsValid() {
// Special case for "length" for slices, arrays to provide the same behaviour as JavaScript engines
// where the "length" method is implicit.
if name == "length" {
switch ctx.Kind() {
case reflect.Slice, reflect.Array, reflect.String:
return reflect.ValueOf(ctx.Len()), true
}
}
return zero, false
}

Expand Down
21 changes: 21 additions & 0 deletions eval_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,27 @@ var evalTests = []Test{
nil, nil, nil,
"C",
},
{
"length method on a slice, like with JS engines",
"Length: {{arr.length}}",
map[string]interface{}{"arr": []int{0, 1, 2}},
nil, nil, nil,
`Length: 3`,
},
{
"length method on an array, like with JS engines",
"Length: {{arr.length}}",
map[string]interface{}{"arr": [...]int{0, 1, 2, 3}},
nil, nil, nil,
`Length: 4`,
},
{
"length method on a string, like with JS engines",
"Length: {{str.length}}",
map[string]interface{}{"str": "abcde"},
nil, nil, nil,
`Length: 5`,
},

// @todo Test with a "../../path" (depth 2 path) while context is only depth 1
}
Expand Down