Skip to content

Commit

Permalink
Allow for fmt.Stringer types in string comparisons (#30)
Browse files Browse the repository at this point in the history
* Allow for fmt.Stringer types in string comparisons

This will allow for string comparison of any types that implement the
String() method.

* fix typo

* call getString in IN
  • Loading branch information
mstory21 authored Nov 20, 2022
1 parent 71e8e56 commit 08cf1ea
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 10 deletions.
2 changes: 1 addition & 1 deletion parser/operation.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ func newErrInvalidOperand(val Operand, typeObj interface{}) *ErrInvalidOperand {
}

func (e *ErrInvalidOperand) Error() string {
return fmt.Sprintf("Operand %v is not the correc type. Expected: %s, Actual: %s",
return fmt.Sprintf("Operand %v is not the correct type. Expected: %s, Actual: %s",
e.Val,
reflect.TypeOf(e.typeObj).String(),
reflect.TypeOf(e.Val).String(),
Expand Down
30 changes: 21 additions & 9 deletions parser/string_operation.go
Original file line number Diff line number Diff line change
@@ -1,24 +1,36 @@
package parser

import (
"fmt"
"strings"
)

type StringOperation struct {
NullOperation
}

func (o *StringOperation) getString(operand Operand) (string, error) {
switch opVal := operand.(type) {
case string:
return opVal, nil
case fmt.Stringer:
return opVal.String(), nil
default:
return "", newErrInvalidOperand(operand, opVal)
}
}

func (o *StringOperation) get(left Operand, right Operand) (string, string, error) {
if left == nil {
return "", "", ErrEvalOperandMissing
}
leftVal, ok := left.(string)
if !ok {
return "", "", newErrInvalidOperand(left, leftVal)
leftVal, err := o.getString(left)
if err != nil {
return "", "", err
}
rightVal, ok := right.(string)
if !ok {
return "", "", newErrInvalidOperand(right, rightVal)
rightVal, err := o.getString(right)
if err != nil {
return "", "", err
}
return strings.ToLower(leftVal), strings.ToLower(rightVal), nil

Expand Down Expand Up @@ -97,9 +109,9 @@ func (o *StringOperation) EW(left Operand, right Operand) (bool, error) {
}

func (o *StringOperation) IN(left Operand, right Operand) (bool, error) {
leftVal, ok := left.(string)
if !ok {
return false, newErrInvalidOperand(left, leftVal)
leftVal, err := o.getString(left)
if err != nil {
return false, err
}

rightVal, ok := right.([]string)
Expand Down

0 comments on commit 08cf1ea

Please sign in to comment.