Implement in operator for maps
This commit is contained in:
parent
da8391fc37
commit
979e7aa33e
@ -212,7 +212,7 @@ In this case, the expression will return the content of the `title` variable if
|
|||||||
|
|
||||||
### The `in` operator
|
### 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 -->
|
#("H" in "Hello") <!-- Returns true -->
|
||||||
|
10
expr.go
10
expr.go
@ -67,6 +67,12 @@ func (t *Template) performOp(a, b reflect.Value, op ast.Operator) (any, error) {
|
|||||||
} else {
|
} else {
|
||||||
return nil, t.posError(op, "%w (%s and %s)", ErrTypeMismatch, a.Type(), b.Type())
|
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:
|
case reflect.String:
|
||||||
if a.Kind() != reflect.String {
|
if a.Kind() != reflect.String {
|
||||||
return nil, t.posError(op, "%w (%s and %s)", ErrTypeMismatch, a.Type(), b.Type())
|
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":
|
case "in":
|
||||||
if a.Kind() == reflect.String && b.Kind() == reflect.String {
|
if a.Kind() == reflect.String && b.Kind() == reflect.String {
|
||||||
return strings.Contains(b.String(), a.String()), nil
|
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++ {
|
for i := 0; i < b.Len(); i++ {
|
||||||
if a.Equal(b.Index(i)) {
|
if a.Equal(b.Index(i)) {
|
||||||
return true, nil
|
return true, nil
|
||||||
|
Loading…
Reference in New Issue
Block a user