Implement in operator for maps

This commit is contained in:
Elara 2023-11-03 18:33:41 -07:00
parent da8391fc37
commit 979e7aa33e
2 changed files with 10 additions and 2 deletions

View File

@ -212,7 +212,7 @@ In this case, the expression will return the content of the `title` variable if
### The `in` operator
Salix's `in` operator allows you to check if a slice or array contains a specific element, or if a string contains a substring. Here's one example:
Salix's `in` operator allows you to check if a slice or array contains an element, if a map contains a key, or if a string contains a substring. Here's one example:
```
#("H" in "Hello") <!-- Returns true -->

10
expr.go
View File

@ -67,6 +67,12 @@ func (t *Template) performOp(a, b reflect.Value, op ast.Operator) (any, error) {
} else {
return nil, t.posError(op, "%w (%s and %s)", ErrTypeMismatch, a.Type(), b.Type())
}
case reflect.Map:
if a.CanConvert(b.Type().Key()) {
a = a.Convert(b.Type().Key())
} else {
return nil, t.posError(op, "%w (%s and %s)", ErrTypeMismatch, a.Type(), b.Type())
}
case reflect.String:
if a.Kind() != reflect.String {
return nil, t.posError(op, "%w (%s and %s)", ErrTypeMismatch, a.Type(), b.Type())
@ -179,7 +185,9 @@ func (t *Template) performOp(a, b reflect.Value, op ast.Operator) (any, error) {
case "in":
if a.Kind() == reflect.String && b.Kind() == reflect.String {
return strings.Contains(b.String(), a.String()), nil
} else {
} else if b.Kind() == reflect.Map {
return b.MapIndex(a).IsValid(), nil
} else if b.Kind() == reflect.Slice || b.Kind() == reflect.Array {
for i := 0; i < b.Len(); i++ {
if a.Equal(b.Index(i)) {
return true, nil