### Install Expr Package Source: https://expr-lang.org Add the Expr expression language library to your Go project using the go get command. ```go go get github.com/expr-lang/expr ``` -------------------------------- ### Check if string has prefix Source: https://expr-lang.org/docs/language-definition Returns true if the string starts with the specified prefix, false otherwise. ```Expr hasPrefix("HelloWorld", "Hello") == true ``` -------------------------------- ### Example of Now Function with Timezone Source: https://expr-lang.org/docs/configuration Shows the `now()` function returning the current time, respecting the timezone configured during compilation. ```expr now() // returns the current time in the specified timezone ``` -------------------------------- ### Variable Declaration with 'let' Source: https://expr-lang.org/docs/language-definition Explains how to declare variables using the 'let' keyword. Variables must start with a letter or underscore and can contain letters, digits, and underscores. ```expr let x = 42; x * 2 ``` ```expr let x = 42; let y = 2; x * y ``` ```expr let name = user.Name | lower() | split(" "); "Hello, " + name[0] + "!" ``` -------------------------------- ### Example of Date Parsing with Timezone Source: https://expr-lang.org/docs/configuration Demonstrates how the `date()` function parses a string into a date object using the timezone specified during compilation. ```expr date("2024-11-23 12:00:00") // parses the date in the specified timezone ``` -------------------------------- ### Example of Function Transformation with Context Source: https://expr-lang.org/docs/configuration Illustrates how `expr.WithContext` transforms a function call by prepending the context variable (e.g., `ctx`) as the first argument, provided the function signature accepts it. ```expr customFunc(42) // will be transformed to customFunc(ctx, 42) ``` -------------------------------- ### Range Operator for Integer Sequences Source: https://expr-lang.org/docs/language-definition Demonstrates the range operator '..' for creating sequences of integers. The range is inclusive of the start and end values. ```expr 1..3 == [1, 2, 3] ``` -------------------------------- ### Get keys from a map Source: https://expr-lang.org/docs/language-definition Returns an array containing the keys of the map. ```expr keys({"name": "John", "age": 30}) == ["name", "age"] ``` -------------------------------- ### Traverse AST with ast.Walk after Parsing Source: https://expr-lang.org/docs/visitor Parse an expression string and use ast.Walk to traverse the resulting AST with a custom Visitor. This example collects identifiers from the parsed expression. ```go tree, err := parser.Parse(`foo + bar`) if err != nil { panic(err) } v := &Visitor{} ast.Walk(&tree.Node, v) fmt.Println(v.Identifiers) // [foo, bar] ``` -------------------------------- ### Get current date and time Source: https://expr-lang.org/docs/language-definition The 'now()' function returns the current date and time as a time.Time value. ```Expr now().Year() == 2024 ``` -------------------------------- ### Get Timezone String Source: https://expr-lang.org/docs/language-definition Returns the timezone of the given string. Refer to the documentation for a list of available timezones. ```expression timezone("Europe/Zurich") ``` ```expression timezone("UTC") ``` -------------------------------- ### Example of Runtime Function Evaluation Source: https://expr-lang.org/docs/configuration Illustrates a function call that will be evaluated at runtime because one of its arguments is a variable (`x`). This contrasts with compile-time constant evaluation. ```expr fib(x) // will **not** be transformed and will be evaluated at runtime ``` -------------------------------- ### Get values from a map Source: https://expr-lang.org/docs/language-definition Returns an array containing the values of the map. ```expr values({"name": "John", "age": 30}) == ["John", 30] ``` -------------------------------- ### Get First Element of Array Source: https://expr-lang.org/docs/language-definition Returns the first element from an array. Returns `nil` if the array is empty. ```expression first([1, 2, 3]) == 1 ``` -------------------------------- ### Example of Compile-Time Constant Evaluation Source: https://expr-lang.org/docs/configuration Demonstrates compile-time evaluation for a function call with constant arguments. `fib(10)` is evaluated to `55` during compilation. ```expr fib(10) // will be transformed to 55 during the compilation ``` -------------------------------- ### Define Custom Decimal Type Source: https://expr-lang.org/docs/patch Define a custom struct `Decimal` to be used in expressions. This is a prerequisite for the advanced patching example. ```go type Decimal struct { Value int } ``` -------------------------------- ### Array Slicing with ':' Source: https://expr-lang.org/docs/language-definition Illustrates the slice operator ':' for extracting sub-arrays. Supports various combinations of start and end indices, including omitting them for full or partial slices. ```expr array[1:4] == [2, 3, 4] ``` ```expr array[1:-1] == [2, 3, 4] ``` ```expr array[:3] == [1, 2, 3] ``` ```expr array[3:] == [4, 5] ``` ```expr array[:] == array ``` -------------------------------- ### Find index of first substring Source: https://expr-lang.org/docs/language-definition Returns the starting index of the first occurrence of a substring within a string. Returns -1 if the substring is not found. ```Expr indexOf("apple pie", "pie") == 6 ``` -------------------------------- ### Get Absolute Value Source: https://expr-lang.org/docs/language-definition Returns the absolute value of a number. Useful for ensuring positive values. ```expression abs(-5) == 5 ``` -------------------------------- ### Find index of last substring Source: https://expr-lang.org/docs/language-definition Returns the starting index of the last occurrence of a substring within a string. Returns -1 if the substring is not found. ```Expr lastIndexOf("apple pie apple", "apple") == 10 ``` -------------------------------- ### get(v, index) Source: https://expr-lang.org/docs/language-definition Retrieves the element at the specified index from an array or map `v`. If the index is out of range, returns `nil`. Or the key does not exist, returns `nil`. ```APIDOC ## get(v, index) ### Description Retrieves the element at the specified index from an array or map `v`. If the index is out of range, returns `nil`. Or the key does not exist, returns `nil`. ### Parameters #### Path Parameters - **v** (any) - Required - The array or map to retrieve the element from. - **index** (any) - Required - The index or key of the element to retrieve. ### Request Example ``` get([1, 2, 3], 1) get({"name": "John", "age": 30}, "name") ``` ### Response #### Success Response (200) - **result** (any) - The element at the specified index or key, or `nil` if not found. ``` -------------------------------- ### Example of Compile-Time Constant Evaluation with Arithmetic Source: https://expr-lang.org/docs/configuration Shows compile-time evaluation of a function call involving arithmetic operations on constants. `fib(12+12)` is evaluated to `267914296` during compilation. ```expr fib(12+12) // will be transformed to 267914296 during the compilation ``` -------------------------------- ### Example Expression for Type Checking Source: https://expr-lang.org/docs/configuration This expression demonstrates array access. Arrays created in Expr are of type `[]any`. The type checker might not flag type mismatches if `WarnOnAny()` is not used. ```expr let arr = [1, 2, 3]; arr[0] ``` -------------------------------- ### Get element by index or key Source: https://expr-lang.org/docs/language-definition Retrieves an element from an array or map using its index or key. Returns `nil` if the index is out of range or the key does not exist. ```expr get([1, 2, 3], 1) == 2 ``` ```expr get({"name": "John", "age": 30}, "name") == "John" ``` -------------------------------- ### Example Expression for Type Casting Source: https://expr-lang.org/docs/configuration This expression explicitly casts the first element of an array to an integer. This is necessary when `WarnOnAny()` is enabled and the expression's return type needs to be specific. ```expr let arr = [1, 2, 3]; int(arr[0]) ``` -------------------------------- ### Compile and Run Expression with Decimal Patcher Source: https://expr-lang.org/docs/patch Compile and run an expression using a custom `DecimalPatcher` and an environment containing `Decimal` values and an `add` function. This demonstrates transforming arithmetic operations. ```go env := map[string]interface{}{ "a": Decimal{1}, "b": Decimal{2}, "c": Decimal{3}, "add": func(x, y Decimal) Decimal { return Decimal{x.Value + y.Value} }, } code := `a + b + c` program, err := expr.Compile(code, expr.Env(env), expr.Patch(DecimalPatcher{})) if err != nil { panic(err) } output, err := expr.Run(program, env) if err != nil { panic(err) } fmt.Println(output) // Decimal{6} ``` -------------------------------- ### Compile and Run a Simple Expression in Go Source: https://expr-lang.org/docs/getting-started Compile a basic arithmetic expression and run it. Reuse compiled programs for performance in critical applications. ```go program, err := expr.Compile(`2 + 2`) if err != nil { panic(err) } output, err := expr.Run(program, nil) if err != nil { panic(err) } fmt.Print(output) // 4 ``` -------------------------------- ### Get Minimum of Two Numbers Source: https://expr-lang.org/docs/language-definition Returns the minimum of two numbers. Used for comparisons. ```expression min(5, 7) == 5 ``` -------------------------------- ### Implement Advanced Decimal Patcher Source: https://expr-lang.org/docs/patch Implement a visitor to transform binary addition operations between `Decimal` types into `add` function calls. Ensure correct type setting for recursive patching. ```go type DecimalPatcher struct{} var decimalType = reflect.TypeOf(Decimal{}) func (DecimalPatcher) Visit(node *ast.Node) { if n, ok := (*node).(*ast.BinaryNode); ok && n.Operator == "+" { if !n.Left.Type().AssignableTo(decimalType) { return // skip, left side is not a Decimal } if !n.Right.Type().AssignableTo(decimalType) { return // skip, right side is not a Decimal } callNode := &ast.CallNode{ Callee: &ast.IdentifierNode{Value: "add"}, Arguments: []ast.Node{n.Left, n.Right}, } ast.Patch(node, callNode) (*node).SetType(decimalType) // set the type, so the patcher can be applied recursively } } ``` -------------------------------- ### Get Maximum of Two Numbers Source: https://expr-lang.org/docs/language-definition Returns the maximum of two numbers. Used for comparisons. ```expression max(5, 7) == 7 ``` -------------------------------- ### Using Go Functions and Slices in Expressions Source: https://expr-lang.org/docs/getting-started Integrate Go functions like `fmt.Sprintf` and slices within Expr expressions. Ensure the function and slice are available in the environment. ```go env := map[string]any{ "greet": "Hello, %v!", "names": []string{"world", "you"}, "sprintf": fmt.Sprintf, } program, err := expr.Compile(`sprintf(greet, names[0])`, expr.Env(env)) if err != nil { panic(err) } output, err := expr.Run(program, env) if err != nil { panic(err) } fmt.Print(output) // Hello, world! ``` -------------------------------- ### Get Last Element of Array Source: https://expr-lang.org/docs/language-definition Returns the last element from an array. Returns `nil` if the array is empty. ```expression last([1, 2, 3]) == 3 ``` -------------------------------- ### take(array, n) Source: https://expr-lang.org/docs/language-definition Returns the first `n` elements from an array. If the array has fewer than `n` elements, it returns the whole array. ```APIDOC ## take(array, n) ### Description Returns the first `n` elements from an array. If the array has fewer than `n` elements, returns the whole array. ### Parameters #### Path Parameters - **array** (array) - Required - The input array. - **n** (int) - Required - The number of elements to take from the beginning of the array. ### Request Example ``` take([1, 2, 3, 4], 2) ``` ### Response #### Success Response (200) - **result** (array) - An array containing the first `n` elements. ``` -------------------------------- ### Compile Expression with Basic Patching Source: https://expr-lang.org/docs/patch Compile an expression and apply a custom patcher to modify it before execution. The patcher replaces a specific identifier with a constant value. ```go program, err := expr.Compile(`foo + bar`) ``` ```go type FooPatcher struct{} func (FooPatcher) Visit(node *ast.Node) { if n, ok := (*node).(*ast.IdentifierNode); ok && n.Value == "foo" { ast.Patch(node, &ast.IntegerNode{Value: 42}) } } ``` ```go program, err := expr.Compile(`foo + bar`, expr.Patch(FooPatcher{})) ``` -------------------------------- ### Reusing Compiled Programs with Struct Environments Source: https://expr-lang.org/docs/getting-started Demonstrates reusing a compiled Expr program with different instances of a struct environment. Compiled programs are safe for concurrent use. ```go type Env struct { X int Y int } program, err := expr.Compile(`X + Y`, expr.Env(Env{})) if err != nil { panic(err) } output, err := expr.Run(program, Env{1, 2}) if err != nil { panic(err) } fmt.Print(output) // 3 output, err = expr.Run(program, Env{3, 4}) if err != nil { panic(err) } fmt.Print(output) // 7 ``` -------------------------------- ### Compile with Struct Environment - Go Source: https://expr-lang.org/docs/environment Compile an expression using a struct as the environment. Expr uses reflection to discover fields and methods. Ensure the environment type passed to `expr.Env` matches the one used for running. ```go program, err := expr.Compile(code, expr.Env(Env{})) ``` ```go output, err := expr.Run(program, Env{ UpdatedAt: time.Now(), Posts: []Post{{Title: "Hello, World!"}}, Map: map[string]string{"tag1": "value1"}, }) ``` -------------------------------- ### Traverse AST with ast.Walk after Compilation Source: https://expr-lang.org/docs/visitor Compile an expression string and then use ast.Walk to traverse the AST of the compiled program with a custom Visitor. Note that the AST of a compiled program may have been modified by optimizers. ```go program, err := expr.Compile(`foo + bar`) if err != nil { panic(err) } node := program.Node() v := &Visitor{} ast.Walk(&node, v) ``` -------------------------------- ### Create Function with Function Option Source: https://expr-lang.org/docs/functions Use the `expr.Function` option to define a custom function. This method is recommended for performance and allows for compile-time evaluation if marked with `ConstExpr`. ```go atoi := expr.Function( "atoi", func(params ...any) (any, error) { return strconv.Atoi(params[0].(string)) }, ) program, err := expr.Compile(`atoi("42")`, atoi) ``` -------------------------------- ### Using Structs as Environments in Go Source: https://expr-lang.org/docs/getting-started Utilize a Go struct as an environment for Expr expressions, allowing access to struct fields and methods. Methods on the struct become available as functions within the expression. ```go type Env struct { Posts []Post `expr:"posts"` } func (Env) Format(t time.Time) string { // Methods defined on the struct become functions. return t.Format(time.RFC822) } type Post struct { Body string Date time.Time } func main() { code := `map(posts, Format(.Date) + ": " + .Body)` program, err := expr.Compile(code, expr.Env(Env{})) // Pass the struct as an environment. if err != nil { panic(err) } env := Env{ Posts: []Post{ {"Oh My God!", time.Now()}, {"How you doin?", time.Now()}, {"Could I be wearing any more clothes?", time.Now()}, }, } output, err := expr.Run(program, env) if err != nil { panic(err) } fmt.Print(output) } ``` -------------------------------- ### Define Map Environment - Go Source: https://expr-lang.org/docs/environment Use a map as an environment to define variables and functions. The map key is the variable name, and the value's type is inferred. Built-in functions like `fmt.Sprintf` can be included. ```go env := map[string]any{ "UpdatedAt": time.Time{}, "Posts": []Post{}, "tags": map[string]string{}, "sprintf": fmt.Sprintf, } program, err := expr.Compile(code, expr.Env(env)) ``` -------------------------------- ### Get length of value Source: https://expr-lang.org/docs/language-definition Returns the length of an array, map, or string. For arrays and maps, it's the number of elements; for strings, it's the number of characters. ```expr len([1, 2, 3]) == 3 ``` ```expr len({"name": "John", "age": 30}) == 2 ``` ```expr len("Hello") == 5 ``` -------------------------------- ### Type Checking with Environment in Go Source: https://expr-lang.org/docs/getting-started Demonstrates Expr's type safety by attempting to compile an expression that concatenates a string and an integer, which will panic. ```go env := map[string]any{ "name": "Anton", "age": 35, } program, err := expr.Compile(`name + age`, expr.Env(env)) if err != nil { panic(err) // Will panic with "invalid operation: string + int" } ``` -------------------------------- ### Implement Visitor to Collect Identifiers Source: https://expr-lang.org/docs/visitor Implement the Visitor interface to collect all identifiers used in an expression. The Visit method is called for each node in the AST. ```go type Visitor struct { Identifiers []string } func (v *Visitor) Visit(node *ast.Node) { if n, ok := (*node).(*ast.IdentifierNode); ok { v.Identifiers = append(v.Identifiers, n.Value) } } ``` -------------------------------- ### Define Function by Reusing Existing Go Function Source: https://expr-lang.org/docs/functions Assign an existing Go function directly as the implementation for an Expr function. This is a concise way to expose utility functions. ```go atoi := expr.Function( "atoi", func(params ...any) (any, error) { return strconv.Atoi(params[0].(string)) }, strconv.Atoi, ) ``` -------------------------------- ### Trim prefix from string Source: https://expr-lang.org/docs/language-definition Removes a specified prefix from the beginning of a string if it exists. ```Expr trimPrefix("HelloWorld", "Hello") == "World" ``` -------------------------------- ### Evaluate Expression in One Step with Eval Source: https://expr-lang.org/docs/getting-started Use `expr.Eval` for one-off expressions that require both compilation and execution in a single step. It accepts an environment. ```go output, err := expr.Eval(`2 + 2`, env) ``` -------------------------------- ### Accessing Struct Fields and Map Items Source: https://expr-lang.org/docs/language-definition Illustrates accessing struct fields and map items using dot (.) or bracket ([]) notation. The dot notation is generally preferred for readability. ```expr user.Name ``` ```expr user["Name"] ``` -------------------------------- ### Accessing Environment Variables with '$env' Source: https://expr-lang.org/docs/language-definition Introduces the '$env' map, which holds all variables passed to the expression. It can be used for accessing variables by name, including those with spaces, and checking for their existence. ```expr foo.Name == $env["foo"].Name ``` ```expr $env["var with spaces"] ``` ```expr 'foo' in $env ``` -------------------------------- ### Compile Expression with Context Integration Source: https://expr-lang.org/docs/configuration Use `expr.WithContext("ctx")` to enable passing a context object to user-defined functions. The context variable name (e.g., "ctx") must be defined in the environment. This is useful for managing function execution lifecycles, especially for I/O-bound operations. ```go env := map[string]any{ "ctx": context.Background(), "customFunc": func(ctx context.Context, a int) int { return a }, } program, err := expr.Compile(code, expr.Env(env), expr.WithContext("ctx")) ``` -------------------------------- ### Get type of a value Source: https://expr-lang.org/docs/language-definition Returns the type of the given value. Supported types include nil, bool, int, uint, float, string, array, and map. Named types and structs return their type name. ```expr type(42) == "int" ``` ```expr type("hello") == "string" ``` ```expr type(now()) == "time.Time" ``` -------------------------------- ### Take first N elements from an array Source: https://expr-lang.org/docs/language-definition Returns the first `n` elements from an array. If the array has fewer than `n` elements, the whole array is returned. ```expr take([1, 2, 3, 4], 2) == [1, 2] ``` -------------------------------- ### Pass Variables to an Expression in Go Source: https://expr-lang.org/docs/getting-started Compile and run an expression that uses variables defined in a Go map environment. The environment must be passed to both Compile and Run. ```go env := map[string]any{ "foo": 100, "bar": 200, } program, err := expr.Compile(`foo + bar`, expr.Env(env)) if err != nil { panic(err) } output, err := expr.Run(program, env) if err != nil { panic(err) } fmt.Print(output) // 300 ``` -------------------------------- ### Map Array Elements Source: https://expr-lang.org/docs/language-definition Creates a new array by applying a predicate to each element of the input array. ```expression map(tweets, {.Size}) ``` -------------------------------- ### Compile Expression with Specific Return Type and Warn on Any Source: https://expr-lang.org/docs/configuration Use `expr.WarnOnAny()` in conjunction with specific return type options (e.g., `expr.AsInt()`) to receive a compile-time error if the expression's return type is `any`. This enforces stricter type checking. ```go program, err := expr.Compile(code, expr.AsInt(), expr.WarnOnAny()) ``` -------------------------------- ### fromPairs(array) Source: https://expr-lang.org/docs/language-definition Converts an array of key-value pairs to a map. ```APIDOC ## fromPairs(array) ### Description Converts an array of key-value pairs to a map. ### Parameters #### Path Parameters - **array** (array) - Required - The array of key-value pairs to convert. ### Request Example ``` fromPairs([["name", "John"], ["age", 30]]) ``` ### Response #### Success Response (200) - **result** (map) - The map created from the key-value pairs. ``` -------------------------------- ### Define Custom Function in Environment Source: https://expr-lang.org/docs/functions Add a custom function directly to the environment map. This is a straightforward way to make a Go function available within Expr. ```go env := map[string]any{ "add": func(a, b int) int { return a + b }, } ``` -------------------------------- ### toBase64(v) Source: https://expr-lang.org/docs/language-definition Encodes the string `v` into Base64 format. ```APIDOC ## toBase64(v) ### Description Encodes the string `v` into Base64 format. ### Parameters #### Path Parameters - **v** (string) - Required - The string to encode. ### Request Example ``` toBase64("Hello World") ``` ### Response #### Success Response (200) - **result** (string) - The Base64 encoded string. ``` -------------------------------- ### Array and Slice Element Access Source: https://expr-lang.org/docs/language-definition Demonstrates accessing array and slice elements by index, including support for negative indices to access elements from the end. ```expr array[0] // first element ``` ```expr array[-1] // last element ``` -------------------------------- ### Define Function with Multiple Signatures Source: https://expr-lang.org/docs/functions Provide multiple function signatures for a single Expr function to handle different input types. The implementation should use type assertions to manage these variations. ```go toInt := expr.Function( "toInt", func(params ...any) (any, error) { switch params[0].(type) { case float64: return int(params[0].(float64)), nil case string: return strconv.Atoi(params[0].(string)) } return nil, fmt.Errorf("invalid type") }, new(func(float64) int), new(func(string) int), ) ``` -------------------------------- ### Define Function with Specific Signature Source: https://expr-lang.org/docs/functions Specify the argument and return types for a function using `expr.Function`. This improves type safety and allows the type checker to correctly infer function behavior. ```go atoi := expr.Function( "atoi", func(params ...any) (any, error) { return strconv.Atoi(params[0].(string)) }, new(func(string) int), ) ``` -------------------------------- ### Convert string to uppercase Source: https://expr-lang.org/docs/language-definition Converts all characters in a string to their uppercase equivalents. ```Expr upper("hello") == "HELLO" ``` -------------------------------- ### Define Struct Environment - Go Source: https://expr-lang.org/docs/environment Define a struct to be used as an environment. Fields in the struct become variables, and methods become functions accessible to the expression. The `expr` tag can rename fields. ```go type Env struct { UpdatedAt time.Time Posts []Post Map map[string]string `expr:"tags"` } ``` ```go func (Env) Format(t time.Time) string { return t.Format(time.RFC822) } ``` ```go type Env struct { Helpers } type Helpers struct{} func (Helpers) Format(t time.Time) string { return t.Format(time.RFC822) } ``` -------------------------------- ### Define Custom Function on a Struct Source: https://expr-lang.org/docs/functions Define a custom function as a method on a Go struct. This approach organizes functions within a specific type. ```go type Env struct{} func (Env) Add(a, b int) int { return a + b } ``` -------------------------------- ### Access date components Source: https://expr-lang.org/docs/language-definition Methods like Year(), Month(), Day(), Hour(), Minute(), Second(), Weekday(), and YearDay() can be used to extract specific components from a date object. ```Expr date("2023-08-14").Year() == 2023 ``` -------------------------------- ### Accessing Fields in Map Environment - Expr Source: https://expr-lang.org/docs/environment Demonstrates how fields are accessed in a map-based environment. Nested fields in maps return `nil` for unknown keys, while structs error on unknown fields by default. ```expr object.field object.unknown struct.field struct.unknown foobar ``` -------------------------------- ### bitxor(int, int) Source: https://expr-lang.org/docs/language-definition Returns the values resulting from the bitwise XOR operation. ```APIDOC ## bitxor(int, int) ### Description Returns the values resulting from the bitwise XOR operation. ### Parameters #### Path Parameters - **a** (int) - Required - The first integer. - **b** (int) - Required - The second integer. ### Request Example ``` bitxor(0b1010, 0b1100) ``` ### Response #### Success Response (200) - **result** (int) - The result of the bitwise XOR operation. ``` -------------------------------- ### Optional Chaining with '?.' Source: https://expr-lang.org/docs/language-definition Explains optional chaining using the '?.' operator, which safely accesses nested properties or map items, returning nil if any part of the chain is nil. ```expr author.User?.Name ``` -------------------------------- ### fromBase64(v) Source: https://expr-lang.org/docs/language-definition Decodes the Base64 encoded string `v` back to its original form. ```APIDOC ## fromBase64(v) ### Description Decodes the Base64 encoded string `v` back to its original form. ### Parameters #### Path Parameters - **v** (string) - Required - The Base64 encoded string to decode. ### Request Example ``` fromBase64("SGVsbG8gV29ybGQ=") ``` ### Response #### Success Response (200) - **result** (string) - The decoded string. ``` -------------------------------- ### int(v) Source: https://expr-lang.org/docs/language-definition Returns the integer value of a number or a string. ```APIDOC ## int(v) ### Description Returns the integer value of a number or a string. ### Parameters #### Path Parameters - **v** (any) - Required - The number or string to convert to an integer. ### Request Example ``` int("123") ``` ### Response #### Success Response (200) - **result** (int) - The integer value. ``` -------------------------------- ### Convert string to lowercase Source: https://expr-lang.org/docs/language-definition Converts all characters in a string to their lowercase equivalents. ```Expr lower("HELLO") == "hello" ``` -------------------------------- ### Convert string to date Source: https://expr-lang.org/docs/language-definition The 'date()' function converts a string to a date. Optional format and timezone arguments can be provided. If format is omitted, specific default formats are expected. ```Expr date("2023-08-14") ``` ```Expr date("15:04:05") ``` ```Expr date("2023-08-14T00:00:00Z") ``` ```Expr date("2023-08-14 00:00:00", "2006-01-02 15:04:05", "Europe/Zurich") ``` -------------------------------- ### string(v) Source: https://expr-lang.org/docs/language-definition Converts the given value `v` into a string representation. ```APIDOC ## string(v) ### Description Converts the given value `v` into a string representation. ### Parameters #### Path Parameters - **v** (any) - Required - The value to convert to a string. ### Request Example ``` string(123) ``` ### Response #### Success Response (200) - **result** (string) - The string representation of the value. ``` -------------------------------- ### Compile Expression with Operator Overloading Source: https://expr-lang.org/docs/patch Compile an expression using the built-in operator overloading feature to replace a standard operator with a custom function call. This simplifies the process compared to manual patching for operators. ```go program, err := expr.Compile(code, expr.Env(env), expr.Operator("+", "add")) ``` -------------------------------- ### bitand(int, int) Source: https://expr-lang.org/docs/language-definition Returns the values resulting from the bitwise AND operation. ```APIDOC ## bitand(int, int) ### Description Returns the values resulting from the bitwise AND operation. ### Parameters #### Path Parameters - **a** (int) - Required - The first integer. - **b** (int) - Required - The second integer. ### Request Example ``` bitand(0b1010, 0b1100) ``` ### Response #### Success Response (200) - **result** (int) - The result of the bitwise AND operation. ``` -------------------------------- ### Bitwise AND operation Source: https://expr-lang.org/docs/language-definition Returns the result of a bitwise AND operation between two integers. ```expr bitand(0b1010, 0b1100) == 0b1000 ``` -------------------------------- ### reverse(array) Source: https://expr-lang.org/docs/language-definition Returns a new reversed copy of the array. ```APIDOC ## reverse(array) ### Description Return new reversed copy of the array. ### Parameters #### Path Parameters - **array** (array) - Required - The input array. ### Request Example ``` reverse([3, 1, 4]) ``` ### Response #### Success Response (200) - **result** (array) - A new array with the elements in reverse order. ``` -------------------------------- ### Nil Coalescing with '??' Source: https://expr-lang.org/docs/language-definition Demonstrates the nil coalescing operator '??', which provides a default value if the left-hand expression evaluates to nil. ```expr author.User?.Name ?? "Anonymous" ``` -------------------------------- ### Date and time operations Source: https://expr-lang.org/docs/language-definition Perform arithmetic and comparisons on dates. Use 'now()' for current time and 'duration()' for time intervals. ```Expr createdAt - now() ``` ```Expr createdAt + duration("1h") ``` ```Expr createdAt > now() - duration("1h") ``` -------------------------------- ### len(v) Source: https://expr-lang.org/docs/language-definition Returns the length of an array, a map, or a string. ```APIDOC ## len(v) ### Description Returns the length of an array, a map or a string. ### Parameters #### Path Parameters - **v** (any) - Required - The array, map, or string to get the length of. ### Request Example ``` len([1, 2, 3]) len({"name": "John", "age": 30}) len("Hello") ``` ### Response #### Success Response (200) - **result** (int) - The length of the input. ``` -------------------------------- ### String Literals in Expr Source: https://expr-lang.org/docs/language-definition Demonstrates basic string literals enclosed in double quotes, including newline escape sequences. Use backticks for multiline raw strings without escape sequence support. ```expr "Hello\nWorld" ``` ```expr `Hello World` ``` -------------------------------- ### Bitwise OR operation Source: https://expr-lang.org/docs/language-definition Returns the result of a bitwise OR operation between two integers. ```expr bitor(0b1010, 0b1100) == 0b1110 ``` -------------------------------- ### Map Environment with Nested Structures - Go Source: https://expr-lang.org/docs/environment Define a map environment containing nested maps and structs. Expr infers types and allows field access. Accessing unknown fields on maps returns `nil`, while on structs it returns an error unless `AllowUndefinedVariables` is set. ```go env := map[string]any{ "object": map[string]any{ "field": 42, }, "struct": struct { Field int `expr:"field"` }{42}, } ``` -------------------------------- ### Compile Expression with Compile-Time Constant Evaluation Source: https://expr-lang.org/docs/configuration Use `expr.ConstExpr("fib")` to enable compile-time evaluation for specific functions (e.g., "fib"). If all arguments to the function are constants, the function will be evaluated during compilation, and its result will be embedded as a constant in the compiled expression. ```go func fib(n int) int { if n <= 1 { return n } return fib(n-1) + fib(n-2) } env := map[string]any{ "fib": fib, } program, err := expr.Compile(`fib(10)`, expr.Env(env), expr.ConstExpr("fib")) ``` -------------------------------- ### Convert to string Source: https://expr-lang.org/docs/language-definition Converts the given value into its string representation. Useful for displaying or concatenating values of different types. ```expr string(123) == "123" ``` -------------------------------- ### Create duration from string Source: https://expr-lang.org/docs/language-definition The 'duration()' function converts a string representation into a time.Duration value. Valid units include ns, us, ms, s, m, h. ```Expr duration("1h").Seconds() == 3600 ``` -------------------------------- ### keys(map) Source: https://expr-lang.org/docs/language-definition Returns an array containing the keys of the map. ```APIDOC ## keys(map) ### Description Returns an array containing the keys of the map. ### Parameters #### Path Parameters - **map** (map) - Required - The input map. ### Request Example ``` keys({"name": "John", "age": 30}) ``` ### Response #### Success Response (200) - **result** (array) - An array of the map's keys. ``` -------------------------------- ### Membership Check with 'in' Operator Source: https://expr-lang.org/docs/language-definition Shows how to use the 'in' operator to check for the presence of an element within an array or a key within a map. ```expr "John" in ["John", "Jane"] ``` ```expr "name" in {"name": "John", "age": 30} ``` -------------------------------- ### Encode to Base64 Source: https://expr-lang.org/docs/language-definition Encodes the input string into Base64 format. Useful for data transmission or storage. ```expr toBase64("Hello World") == "SGVsbG8gV29ybGQ=" ``` -------------------------------- ### Join Array Elements into String Source: https://expr-lang.org/docs/language-definition Joins an array of strings into a single string using a specified delimiter. If no delimiter is provided, elements are joined with an empty string. ```expression join(["apple", "orange", "grape"], ",") == "apple,orange,grape" ``` ```expression join(["apple", "orange", "grape"]) == "appleorangegrape" ``` -------------------------------- ### Compile Expression with Boolean Return Type Source: https://expr-lang.org/docs/configuration Use `expr.AsBool()` to instruct the type checker to verify the return type of the expression as a boolean. This is common for filter expressions. The output can be safely asserted to bool if type checking passes. ```go program, err := expr.Compile(code, expr.AsBool()) if err != nil { panic(err) } output, err := expr.Run(program, env) if err != nil { panic(err) } ok := output.(bool) // It is safe to assert the output to bool, if the expression is type checked as bool. ``` -------------------------------- ### Convert to float Source: https://expr-lang.org/docs/language-definition Returns the float value of a number or a string. Handles conversion from numeric types and string representations of floating-point numbers. ```expr float("123.45") == 123.45 ``` -------------------------------- ### sort(array[, order]) Source: https://expr-lang.org/docs/language-definition Sorts an array in ascending order. An optional `order` argument can be used to specify the order of sorting: `asc` or `desc`. ```APIDOC ## sort(array[, order]) ### Description Sorts an array in ascending order. Optional `order` argument can be used to specify the order of sorting: `asc` or `desc`. ### Parameters #### Path Parameters - **array** (array) - Required - The array to sort. - **order** (string) - Optional - The order of sorting. Can be `"asc"` or `"desc"`. ### Request Example ``` sort([3, 1, 4]) sort([3, 1, 4], "desc") ``` ### Response #### Success Response (200) - **result** (array) - The sorted array. ``` -------------------------------- ### float(v) Source: https://expr-lang.org/docs/language-definition Returns the float value of a number or a string. ```APIDOC ## float(v) ### Description Returns the float value of a number or a string. ### Parameters #### Path Parameters - **v** (any) - Required - The number or string to convert to a float. ### Request Example ``` float("123.45") ``` ### Response #### Success Response (200) - **result** (float) - The float value. ``` -------------------------------- ### Bytes Literals in Expr Source: https://expr-lang.org/docs/language-definition Shows how to define byte literals using a 'b' prefix. Supports hexadecimal and octal escape sequences for arbitrary byte values. Non-ASCII characters are UTF-8 encoded. ```expr b"abc" // []byte{97, 98, 99} ``` ```expr b"ÿ" // []byte{195, 191} - UTF-8 encoding of ÿ ``` ```expr b"\xff" // []byte{255} b"\x00\x01" // []byte{0, 1} b"\101" // []byte{65} - octal for 'A' ``` -------------------------------- ### fromJSON(v) Source: https://expr-lang.org/docs/language-definition Parses the given JSON string `v` and returns the corresponding value. ```APIDOC ## fromJSON(v) ### Description Parses the given JSON string `v` and returns the corresponding value. ### Parameters #### Path Parameters - **v** (string) - Required - The JSON string to parse. ### Request Example ``` fromJSON('{"name": "John", "age": 30}') ``` ### Response #### Success Response (200) - **result** (any) - The value parsed from the JSON string. ``` -------------------------------- ### Repeat string multiple times Source: https://expr-lang.org/docs/language-definition Repeats a given string a specified number of times. ```Expr repeat("Hi", 3) == "HiHiHi" ``` -------------------------------- ### Split string by delimiter Source: https://expr-lang.org/docs/language-definition Splits a string into an array of substrings based on a delimiter. An optional third argument limits the number of splits. ```Expr split("apple,orange,grape", ",") == ["apple", "orange", "grape"] ``` ```Expr split("apple,orange,grape", ",", 2) == ["apple", "orange,grape"] ``` -------------------------------- ### Array Functions Source: https://expr-lang.org/docs/language-definition Functions for manipulating and querying arrays. ```APIDOC ## all(array, predicate) ### Description Returns **true** if all elements satisfies the predicate. If the array is empty, returns **true**. ### Usage ``` all(tweets, {.Size < 280}) ``` ``` ```APIDOC ## any(array, predicate) ### Description Returns **true** if any elements satisfies the predicate. If the array is empty, returns **false**. ### Usage ``` any(tweets, {.Size > 280}) ``` ``` ```APIDOC ## one(array, predicate) ### Description Returns **true** if _exactly one_ element satisfies the predicate. If the array is empty, returns **false**. ### Usage ``` one(participants, {.Winner}) ``` ``` ```APIDOC ## none(array, predicate) ### Description Returns **true** if _all elements does not_ satisfy the predicate. If the array is empty, returns **true**. ### Usage ``` none(tweets, {.Size > 280}) ``` ``` ```APIDOC ## map(array, predicate) ### Description Returns new array by applying the predicate to each element of the array. ### Usage ``` map(tweets, {.Size}) ``` ``` ```APIDOC ## filter(array, predicate) ### Description Returns new array by filtering elements of the array by predicate. ### Usage ``` filter(users, .Name startsWith "J") ``` ``` ```APIDOC ## find(array, predicate) ### Description Finds the first element in an array that satisfies the predicate. ### Usage ``` find([1, 2, 3, 4], # > 2) == 3 ``` ``` ```APIDOC ## findIndex(array, predicate) ### Description Finds the index of the first element in an array that satisfies the predicate. ### Usage ``` findIndex([1, 2, 3, 4], # > 2) == 2 ``` ``` ```APIDOC ## findLast(array, predicate) ### Description Finds the last element in an array that satisfies the predicate. ### Usage ``` findLast([1, 2, 3, 4], # > 2) == 4 ``` ``` ```APIDOC ## findLastIndex(array, predicate) ### Description Finds the index of the last element in an array that satisfies the predicate. ### Usage ``` findLastIndex([1, 2, 3, 4], # > 2) == 3 ``` ``` ```APIDOC ## groupBy(array, predicate) ### Description Groups the elements of an array by the result of the predicate. ### Usage ``` groupBy(users, .Age) ``` ``` ```APIDOC ## count(array[, predicate]) ### Description Returns the number of elements that satisfy the predicate. ### Usage ``` count(users, .Age > 18) ``` Equivalent to: ``` len(filter(users, .Age > 18)) ``` If the predicate is not given, returns the number of `true` elements in the array. ``` count([true, false, true]) == 2 ``` ``` ```APIDOC ## concat(array1, array2[, ...]) ### Description Concatenates two or more arrays. ### Usage ``` concat([1, 2], [3, 4]) == [1, 2, 3, 4] ``` ``` ```APIDOC ## flatten(array) ### Description Flattens a given array into a one-dimensional array. ### Usage ``` flatten([1, 2, [3, 4]]) == [1, 2, 3, 4] ``` ``` ```APIDOC ## uniq(array) ### Description Removes duplicates from an array. ### Usage ``` uniq([1, 2, 3, 2, 1]) == [1, 2, 3] ``` ``` ```APIDOC ## join(array[, delimiter]) ### Description Joins an array of strings into a single string with the given delimiter. If no delimiter is given, an empty string is used. ### Usage ``` join(["apple", "orange", "grape"], ",") == "apple,orange,grape" join(["apple", "orange", "grape"]) == "appleorangegrape" ``` ``` ```APIDOC ## reduce(array, predicate[, initialValue]) ### Description Applies a predicate to each element in the array, reducing the array to a single value. Optional `initialValue` argument can be used to specify the initial value of the accumulator. If `initialValue` is not given, the first element of the array is used as the initial value. ### Available Variables in Predicate * `#` - the current element * `#acc` - the accumulator * `#index` - the index of the current element ### Usage ``` reduce(1..9, #acc + #) reduce(1..9, #acc + #, 0) ``` ``` ```APIDOC ## sum(array[, predicate]) ### Description Returns the sum of all numbers in the array. ### Usage ``` sum([1, 2, 3]) == 6 ``` If the optional `predicate` argument is given, it is a predicate that is applied on each element of the array before summing. ``` sum(accounts, .Balance) ``` Equivalent to: ``` reduce(accounts, #acc + .Balance, 0) // or sum(map(accounts, .Balance)) ``` ``` ```APIDOC ## mean(array) ### Description Returns the average of all numbers in the array. ### Usage ``` mean([1, 2, 3]) == 2.0 ``` ``` ```APIDOC ## median(array) ### Description Returns the median of all numbers in the array. ### Usage ``` median([1, 2, 3]) == 2.0 ``` ``` ```APIDOC ## first(array) ### Description Returns the first element from an array. If the array is empty, returns `nil`. ### Usage ``` first([1, 2, 3]) == 1 ``` ``` ```APIDOC ## last(array) ### Description Returns the last element from an array. If the array is empty, returns `nil`. ### Usage ``` last([1, 2, 3]) == 3 ``` ``` -------------------------------- ### Timezone Functions Source: https://expr-lang.org/docs/language-definition Functions for handling timezones. ```APIDOC ## timezone(str) ### Description Returns the timezone of the given string `str`. List of available timezones can be found here. ### Usage ``` timezone("Europe/Zurich") timezone("UTC") ``` ### Example with `In()` To convert a date to a different timezone, use the `In()` method: ``` date("2023-08-14 00:00:00").In(timezone("Europe/Zurich")) ``` ``` -------------------------------- ### Convert map to key-value pairs Source: https://expr-lang.org/docs/language-definition Converts a map into an array of key-value pairs. Each pair is represented as a two-element array. ```expr toPairs({"name": "John", "age": 30}) == [["name", "John"], ["age", 30]] ``` -------------------------------- ### bitor(int, int) Source: https://expr-lang.org/docs/language-definition Returns the values resulting from the bitwise OR operation. ```APIDOC ## bitor(int, int) ### Description Returns the values resulting from the bitwise OR operation. ### Parameters #### Path Parameters - **a** (int) - Required - The first integer. - **b** (int) - Required - The second integer. ### Request Example ``` bitor(0b1010, 0b1100) ``` ### Response #### Success Response (200) - **result** (int) - The result of the bitwise OR operation. ```