> ## Documentation Index
> Fetch the complete documentation index at: https://docs.fastgen.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Functions

Examples:

```expr theme={null}
$body.someNumber in 18..45 and $body.someText not in ["admin", "root"]
```

```expr theme={null}
$query.myInput matches "^[A-Z].*"
```

```expr theme={null}
$body.tweets | filter(.Size < 280) | map(.Content) | join(" -- ")
```

```expr theme={null}
filter($body.posts, {now() - .CreatedAt >= 7 * duration("24h")})
```

### Membership Operator

Fields of structs and items of maps can be accessed with `.` operator
or `[]` operator. Elements of arrays and slices can be accessed with
`[]` operator. Negative indices are supported with `-1` being
the last element.

The `in` operator can be used to check if an item is in an array or a map.

```expr theme={null}
$body.Name in list["available-names"]
```

#### Nil coalescing

The `??` operator can be used to return the left-hand side if it is not `nil`,
otherwise the right-hand side is returned.

```expr theme={null}
$body.author?.User?.Name ?? "Anonymous"
```

### Slice Operator

The slice operator `[:]` can be used to access a slice of an array.

For example, variable `array` is `[1, 2, 3, 4, 5]`:

```expr theme={null}
$body.array[1:4] -> [2, 3, 4]
$body.array[1:-1] -> [2, 3, 4]
$body.array[:3] -> [1, 2, 3]
$body.array[3:] -> [4, 5]
$body.array[:] -> array
```

### Pipe Operator

The pipe operator `|` can be used to pass the result of the left-hand side
expression as the first argument of the right-hand side expression.

For example, expression `split(lower(user.Name), " ")` can be written as:

```expr theme={null}
$body.Name | lower() | split(" ")
```

## String Functions

### trim(str\[, chars])

Removes white spaces from both ends of a string `str`.
If the optional `chars` argument is given, it is a string specifying the set of characters to be removed.

```expr theme={null}
trim("  Hello  ") -> "Hello"
trim("__Hello__", "_") -> "Hello"
```

### trimPrefix(str, prefix)

Removes the specified prefix from the string `str` if it starts with that prefix.

```expr theme={null}
trimPrefix("HelloWorld", "Hello") -> "World"
```

### trimSuffix(str, suffix)

Removes the specified suffix from the string `str` if it ends with that suffix.

```expr theme={null}
trimSuffix("HelloWorld", "World") -> "Hello"
```

### upper(str)

Converts all the characters in string `str` to uppercase.

```expr theme={null}
upper("hello") -> "HELLO"
```

### lower(str)

Converts all the characters in string `str` to lowercase.

```expr theme={null}
lower("HELLO") -> "hello"
```

### split(str, delimiter\[, n])

Splits the string `str` at each instance of the delimiter and returns an array of substrings.

```expr theme={null}
split("apple,orange,grape", ",") -> ["apple", "orange", "grape"]
split("apple,orange,grape", ",", 2) -> ["apple", "orange,grape"]
```

### splitAfter(str, delimiter\[, n])

Splits the string `str` after each instance of the delimiter.

```expr theme={null}
splitAfter("apple,orange,grape", ",") -> ["apple,", "orange,", "grape"]
splitAfter("apple,orange,grape", ",", 2) -> ["apple,", "orange,grape"]
```

### replace(str, old, new)

Replaces all occurrences of `old` in string `str` with `new`.

```expr theme={null}
replace("Hello World", "World", "Universe") -> "Hello Universe"
```

### repeat(str, n)

Repeats the string `str` `n` times.

```expr theme={null}
repeat("Hi", 3) -> "HiHiHi"
```

### indexOf(str, substring)

Returns the index of the first occurrence of the substring in string `str` or -1 if not found.

```expr theme={null}
indexOf("apple pie", "pie") -> 6
```

### lastIndexOf(str, substring)

Returns the index of the last occurrence of the substring in string `str` or -1 if not found.

```expr theme={null}
lastIndexOf("apple pie apple", "apple") -> 10
```

### hasPrefix(str, prefix)

Returns `true` if string `str` starts with the given prefix.

```expr theme={null}
hasPrefix("HelloWorld", "Hello") -> true
```

### hasSuffix(str, suffix)

Returns `true` if string `str` ends with the given suffix.

```expr theme={null}
hasSuffix("HelloWorld", "World") -> true
```

## Date Functions

The following operators can be used to manipulate dates:

```expr theme={null}
date("2023-08-14") + duration("1h")
date("2023-08-14") - duration("1h")
date("2023-08-14") - date("2023-08-13") -> duration("24h")
```

### now()

Returns the current date and time.

```expr theme={null}
createdAt > now() - duration("1h")
```

### duration(str)

Returns the duration value of the given string `str` as nanoseconds. Use the additional functions to return it in a different unit.

Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h".

```expr theme={null}
duration("1h") -> 3600000000000
duration("1h").Hours() -> 1
duration("1h3m").Minutes() -> 63
duration("1h3m").Seconds() -> 3780
duration("1h").Milliseconds() -> 3600000
duration("1h").Microseconds() -> 3600000000
```

See also the following utility functions.

```expr theme={null}
duration("1h90s").String() -> "1h90s"
duration("1h90s").Round(duration("1m")).String() -> "1h2m0s"
duration("1h90s").Truncate(duration("1m")).String() -> "1h1m0s"
duration("-1h").Minutes() -> -60
duration("-1h").Abs().Minutes() -> 60
```

### date(str\[, format\[, timezone]])

Converts the given string `str` into a date representation.

If the optional `format` argument is given, it is a string specifying the format of the date.
The format string uses the same formatting rules as the standard
Go [time package](https://pkg.go.dev/time#pkg-constants).

If the optional `timezone` argument is given, it is a string specifying the timezone of the date.

If the `format` argument is not given, the `v` argument must be in one of the following formats:

* 2006-01-02
* 15:04:05
* 2006-01-02 15:04:05
* RFC3339
* RFC822,
* RFC850,
* RFC1123,

```expr theme={null}
date("2023-08-14")
date("15:04:05")
date("2023-08-14T00:00:00Z")
date("2023-08-14 00:00:00", "2006-01-02 15:04:05", "Europe/Zurich")
```

### timezone(str)

Returns the timezone of the given string str. List of available timezones can be found [here](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones).

```expr theme={null}
timezone("Europe/Zurich")
timezone("UTC")
```

To convert a date to a different timezone, use the In() method:

```expr theme={null}
date("2023-08-14 00:00:00").In(timezone("Europe/Zurich"))
```

## Number Functions

### max(n1, n2)

Returns the maximum of the two numbers `n1` and `n2`.

```expr theme={null}
max(5, 7) -> 7
```

### min(n1, n2)

Returns the minimum of the two numbers `n1` and `n2`.

```expr theme={null}
min(5, 7) -> 5
```

### abs(n)

Returns the absolute value of a number.

```expr theme={null}
abs(-5) == 5
```

### ceil(n)

Returns the least integer value greater than or equal to x.

```expr theme={null}
ceil(1.5) == 2.0
```

### floor(n)

Returns the greatest integer value less than or equal to x.

```expr theme={null}
floor(1.5) == 1.0
```

### round(n)

Returns the nearest integer, rounding half away from zero.

```expr theme={null}
round(1.5) == 2.0
```

### sum(array)

Returns the sum of all numbers in the array.

```expr theme={null}
sum([1, 2, 3]) -> 6
```

### mean(array)

Returns the average of all numbers in the array.

```expr theme={null}
mean([1, 2, 3]) -> 2.0
```

### median(array)

Returns the median of all numbers in the array.

```expr theme={null}
median([1, 2, 3]) -> 2.0
```

## Array Functions

### all(array, predicate)

Returns **true** if all elements satisfies the [predicate](#predicate).
If the array is empty, returns **true**.

```expr theme={null}
all($body.tweets, {.Size < 280})
```

### any(array, predicate)

Returns **true** if any elements satisfies the [predicate](#predicate).
If the array is empty, returns **false**.

### one(array, predicate)

Returns **true** if *exactly one* element satisfies the [predicate](#predicate).
If the array is empty, returns **false**.

```expr theme={null}
one(participants, {.Winner})
```

### none(array, predicate)

Returns **true** if *all elements does not* satisfy the [predicate](#predicate).
If the array is empty, returns **true**.

### map(array, predicate)

Returns new array by applying the [predicate](#predicate) to each element of
the array.

```expr theme={null}
map($body.tweets, {.Size})
```

### filter(array, predicate)

Returns new array by filtering elements of the array by [predicate](#predicate).

```expr theme={null}
filter($body.users, .Name startsWith "J")
```

### find(array, predicate)

Finds the first element in an array that satisfies the [predicate](#predicate).

```expr theme={null}
find([1, 2, 3, 4], # > 2) -> 3
```

### findIndex(array, predicate)

Finds the index of the first element in an array that satisfies the [predicate](#predicate).

```expr theme={null}
findIndex([1, 2, 3, 4], # > 2) -> 2
```

### findLast(array, predicate)

Finds the last element in an array that satisfies the [predicate](#predicate).

```expr theme={null}
findLast([1, 2, 3, 4], # > 2) -> 4
```

### findLastIndex(array, predicate)

Finds the index of the last element in an array that satisfies the [predicate](#predicate).

```expr theme={null}
findLastIndex([1, 2, 3, 4], # > 2) -> 3
```

### groupBy(array, predicate)

Groups the elements of an array by the result of the [predicate](#predicate).

```expr theme={null}
groupBy(users, .Age)
```

### count(array, predicate)

Returns the number of elements what satisfies the [predicate](#predicate).

Equivalent to:

```expr theme={null}
len(filter(array, predicate))
```

### concat(array1, array2\[, ...])

Concatenates two or more arrays.

```expr theme={null}
concat([1, 2], [3, 4]) == [1, 2, 3, 4]
```

### join(array\[, delimiter])

Joins an array of strings into a single string with the given delimiter.
If no delimiter is given, an empty string is used.

```expr theme={null}
join(["apple", "orange", "grape"], ",") -> "apple,orange,grape"
join(["apple", "orange", "grape"]) -> "appleorangegrape"
```

### concat(array1, array2\[, ...])

Concatenates two or more arrays.

```expr theme={null}
concat([1, 2], [3, 4]) -> [1, 2, 3, 4]
```

### reduce(array, predicate\[, initialValue])

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.

Following variables are available in the predicate:

* `#` - the current element
* `#acc` - the accumulator
* `#index` - the index of the current element

```expr theme={null}
reduce(1..9, #acc + #)
reduce(1..9, #acc + #, 0)
```

### sum(array)

see [Number Function: sum](#sum-array)

### mean(array)

see [Number Function: mean](#mean-array)

### median(array)

see [Number Function: median](#median-array)

### first(array)

Returns the first element from an array. If the array is empty, returns `nil`.

```expr theme={null}
first([1, 2, 3]) -> 1
```

### last(array)

Returns the last element from an array. If the array is empty, returns `nil`.

```expr theme={null}
last([1, 2, 3]) -> 3
```

### take(array, n)

Returns the first `n` elements from an array. If the array has fewer than `n` elements, returns the whole array.

```expr theme={null}
take([1, 2, 3, 4], 2) -> [1, 2]
```

### reverse(array)

Return new reversed copy of the array.

```expr theme={null}
reverse([3, 1, 4]) -> [4, 1, 3]
reverse(reverse([3, 1, 4])) -> [3, 1, 4]
```

### sort(array\[, order])

Sorts an array in ascending order. Optional `order` argument can be used to specify the order of sorting: `asc`
or `desc`.

```expr theme={null}
sort([3, 1, 4]) -> [1, 3, 4]
sort([3, 1, 4], "desc") -> [4, 3, 1]
```

### sortBy(array, key\[, order])

Sorts an array of maps by a specific key in ascending order. Optional `order` argument can be used to specify the order
of sorting: `asc` or `desc`.

```expr theme={null}
sortBy($body.users, "Age")
sortBy($body.users, "Age", "desc")
```

## Map Functions

### keys(map)

Returns an array containing the keys of the map.

```expr theme={null}
keys({"name": "John", "age": 30}) -> ["name", "age"]
```

### values(map)

Returns an array containing the values of the map.

```expr theme={null}
values({"name": "John", "age": 30}) -> ["John", 30]
```

## Type Conversion Functions

### type(v)

Returns the type of the given value `v`.
Returns on of the following types: `nil`, `bool`, `int`, `uint`, `float`, `string`, `array`, `map`.
For named types and structs, the type name is returned.

```expr theme={null}
type(42) -> "int"
type("hello") -> "string"
type(now()) -> "time.Time"
```

### int(v)

Returns the integer value of a number or a string.

```expr theme={null}
int("123") -> 123
```

### float(v)

Returns the float value of a number or a string.

### string(v)

Converts the given value `v` into a string representation.

```expr theme={null}
string(123) -> "123"
```

### toJSON(v)

Converts the given value `v` to its JSON string representation.

```expr theme={null}
toJSON({"name": "John", "age": 30})
```

### fromJSON(v)

Parses the given JSON string `v` and returns the corresponding value.

```expr theme={null}
fromJSON('{"name": "John", "age": 30}')
```

### toBase64(v)

Encodes the string `v` into Base64 format.

```expr theme={null}
toBase64("Hello World") -> "SGVsbG8gV29ybGQ="
```

### fromBase64(v)

Decodes the Base64 encoded string `v` back to its original form.

```expr theme={null}
fromBase64("SGVsbG8gV29ybGQ=") -> "Hello World"
```

### toPairs(map)

Converts a map to an array of key-value pairs.

```expr theme={null}
toPairs({"name": "John", "age": 30}) -> [["name", "John"], ["age", 30]]
```

### fromPairs(array)

Converts an array of key-value pairs to a map.

```expr theme={null}
fromPairs([["name", "John"], ["age", 30]]) -> {"name": "John", "age": 30}
```

## Miscellaneous Functions

### len(v)

Returns the length of an array, a map or a string.

### get(v, index)

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`.

```expr theme={null}
get([1, 2, 3], 1) -> 2
get({"name": "John", "age": 30}, "name") -> "John"
```

### fallback(v1, v2\[, ...])

Returns the first non-nil value from the arguments given.

```expr theme={null}
fallback(nil, nil, nil, 3, nil) -> 3
fallback($query['non-present-optional-param'], 'myFallbackValue') -> 'myFallbackValue'
$query['non-present-optional-param'] | fallback('myFallbackValue') -> 'myFallbackValue'
```

## Bitwise Functions

### bitand(int, int)

Returns the values resulting from the bitwise AND operation.

```expr theme={null}
bitand(0b1010, 0b1100) == 0b1000
```

### bitor(int, int)

Returns the values resulting from the bitwise OR operation.

```expr theme={null}
bitor(0b1010, 0b1100) == 0b1110
```

### bitxor(int, int)

Returns the values resulting from the bitwise XOR operation.

```expr theme={null}
bitxor(0b1010, 0b1100) == 0b110
```

### bitnand(int, int)

Returns the values resulting from the bitwise AND NOT operation.

```expr theme={null}
bitnand(0b1010, 0b1100) == 0b10
```

### bitnot(int)

Returns the values resulting from the bitwise NOT operation.

```expr theme={null}
bitnot(0b1010) == -0b1011
```

### bitshl(int, int)

Returns the values resulting from the Left Shift operation.

```expr theme={null}
bitshl(0b101101, 2) == 0b10110100
```

### bitshr(int, int)

Returns the values resulting from the Right Shift operation.

```expr theme={null}
bitshr(0b101101, 2) == 0b1011
```

### bitushr(int, int)

Returns the values resulting from the unsigned Right Shift operation.

```expr theme={null}
bitushr(-0b101, 2) == 4611686018427387902
```

## Predicate

The predicate is an expression. It takes one or more arguments and returns a boolean value.
To access the arguments, the `#` symbol is used.

```expr theme={null}
map(0..9, {# / 2})
```

If items of the array is a struct or a map, it is possible to access fields with
omitted `#` symbol (`#.Value` becomes `.Value`).

```expr theme={null}
filter($body.tweets, {len(.Value) > 280})
```

Braces `{` `}` can be omitted:

```expr theme={null}
filter($body.tweets, len(.Value) > 280)
```

## `$env` variable

The `$env` variable is a map of all variables passed to the expression.

```expr theme={null}
foo.Name -> $env["$body"].Name
$env["var with spaces"]
```

## Literals

|         |                                         |
| ------- | --------------------------------------- |
| Comment | <code>/\* \*/</code> or <code>//</code> |
| Boolean | <code>true</code>, <code>false</code>   |
| Integer | <code>42</code>, <code>0x2A</code>      |
| Float   | <code>0.5</code>, <code>.5</code>       |
| String  | <code>"foo"</code>, <code>'bar'</code>  |
| Array   | <code>\[1, 2, 3]</code>                 |
| Map     | <code>\{a: 1, b: 2, c: 3}</code>        |
| Nil     | <code>nil</code>                        |

## Operators

|             |                                                                                                                                           |
| ----------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
| Arithmetic  | <code>+</code>, <code>-</code>, <code>\*</code>, <code>/</code>, <code>%</code> (modulus), <code>^</code> or <code>\*\*</code> (exponent) |
| Comparison  | <code>==</code>, <code>!=</code>, <code>\<</code>, <code>></code>, <code>\<=</code>, <code>>=</code>                                      |
| Logical     | <code>not</code> or <code>!</code>, <code>and</code> or <code>&&</code>, <code>or</code> or <code>\|\|</code>                             |
| Conditional | <code>?:</code> (ternary), <code>??</code> (nil coalescing)                                                                               |
| Membership  | <code>\[]</code>, <code>.</code>, <code>?.</code>, <code>in</code>                                                                        |
| String      | <code>+</code> (concatenation), <code>contains</code>, <code>startsWith</code>, <code>endsWith</code>                                     |
| Regex       | <code>matches</code>                                                                                                                      |
| Range       | <code>..</code>                                                                                                                           |
| Slice       | <code>\[:]</code>                                                                                                                         |
| Pipe        | <code>\|</code>                                                                                                                           |
