Replies: 2 comments
-
It can be resolved by putting options := []expr.Option{
iifFunc, coalesceFunc,
}
code := `Coalesce(email, enterprise_email, aa, IIF(false, "eee", "fff"), "abc")`
program, err = expr.Compile(code, options...)
if err != nil {
fmt.Printf("%v", err)
return
}
output, err = expr.Run(program, env)
if err != nil {
fmt.Printf("%v", err)
return
}
fmt.Printf("%v", output) |
Beta Was this translation helpful? Give feedback.
-
The issue arises because your custom functions Here's how you can solve this:
Here’s the modified implementation: package main
import (
"fmt"
"github.com/antonmedv/expr"
)
// IIF formula
func iifFunc(params ...any) (any, error) {
if len(params) != 3 {
return nil, fmt.Errorf("IIF requires 3 parameters")
}
condition, ok := params[0].(bool)
if !ok {
return nil, fmt.Errorf("first parameter of IIF must be a boolean")
}
if condition {
return params[1], nil
}
return params[2], nil
}
// Coalesce formula
func coalesceFunc(params ...any) (any, error) {
for _, param := range params {
if param != nil {
// Check for non-empty strings
if str, ok := param.(string); ok && str != "" {
return str, nil
}
// Return the first non-nil value
return param, nil
}
}
return nil, fmt.Errorf("no non-nil values in Coalesce")
}
func main() {
// Define the custom functions
functions := map[string]any{
"IIF": iifFunc,
"Coalesce": coalesceFunc,
}
// Example usage
exprStr := `Coalesce(email, enterprise_email, IIF(true, "eee", "fff"), "abc")`
// Compile with both functions
program, err := expr.Compile(exprStr, expr.Env(functions))
if err != nil {
panic(err)
}
// Define the environment
env := map[string]interface{}{
"email": "",
"enterprise_email": "",
}
// Run the program
output, err := expr.Run(program, env)
if err != nil {
panic(err)
}
fmt.Println(output) // Output: eee
} Key Adjustments:
This approach ensures that the |
Beta Was this translation helpful? Give feedback.
-
Hi,
I created two formulas:
IIF
andCoalesce
.They can work when used alone, such as
IIF(true, "eee", "fff")
,Coalesce(email, enterprise_email, aa, "abc")
.However, it can't work when one used in another, such as
Coalesce(email, enterprise_email, aa, IIF(true, "eee", "fff"), "abc")
. How to implement it?Beta Was this translation helpful? Give feedback.
All reactions