add function for any type compare
This commit is contained in:
parent
8b45ed53ee
commit
c4895d22c7
1 changed files with 58 additions and 0 deletions
58
server/helpers/misc.go
Normal file
58
server/helpers/misc.go
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
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")
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue