Taobin-Recipe-Manager/server/helpers/misc.go
2023-11-22 11:18:12 +07:00

58 lines
1.4 KiB
Go

package helpers
import "fmt"
// DynamicCompare compares two values dynamically and returns true if they are equal.
//
// Parameters:
//
// - s: The first value to compare.
//
// - u: The second value to compare.
//
// Returns:
//
// - bool: True if the values are equal, false otherwise.
//
// - error: An error if the values cannot be compared.
func DynamicCompare(s interface{}, u interface{}) (bool, error) {
switch t := s.(type) {
case bool:
u, ok := u.(bool)
if !ok {
return false, fmt.Errorf("[bool] cannot compare %T and %T, %v and %v", t, u, s, u)
}
return t == u, nil
case string:
u, ok := u.(string)
if !ok {
return false, fmt.Errorf("[string] cannot compare %T and %T, %v and %v", t, u, s, u)
}
return t == u, nil
case int:
u, ok := u.(int)
if !ok {
return false, fmt.Errorf("[int] cannot compare %T and %T, %v and %v", t, u, s, u)
}
return t == u, nil
case float64:
u, ok := u.(float64)
if !ok {
return false, fmt.Errorf("[float64] cannot compare %T and %T, %v and %v", t, u, s, u)
}
return t == u, nil
case nil:
return t == u, nil
case []interface{}:
for i := range t {
if ok, err := DynamicCompare(t[i], u); err != nil {
return false, err
} else if !ok {
return false, nil
}
}
default:
return false, fmt.Errorf("[unknown] not in case. Cannot compare %T and %T, %v and %v", t, u, s, u)
}
return false, fmt.Errorf("[unknown] unexpected error")
}