# Built-in functions

## Text-related functions

### isNumber

**Signature:** isNumber(input: primitive) -> boolean

Returns a boolean value indicating whether the input argument can be converted into a number by  the [val](#val) function.

```typescript
// x will have the value true
let x = isNumber("1.5");

// y will have the value false
let y = isNumber("hello");
```

### upper

**Signature:** upper(**self** input: text) -> text

Returns an uppercase version of the input argument.

```typescript
return upper("Hello"); // returns "HELLO"
```

### lower

**Signature:** lower(**self** input: text) -> text

Returns an lowercase version of the input argument.

```typescript
return lower("Hello"); // returns "hello"
```

### val

**Signature:** val(input: text) -> number

Converts the input argument to a number if possible. If the input cannot be meaningfully converted to a number, the function raises a runtime error. To preempt such errors, you can use the [isNumber](#isnumber) function.

The val function will interpret either point or comma as a decimal separator.

```typescript
// x will have the numeric value 1.5
let x = val("1.5"); 

// y will have the numeric value 3.2
let y = val("3,2"); 

// ERROR: The value of type text could not be converted to number.
let z = val("hello");
```

### len

**Signature**: len(**self** input: text) ->  number

Returns the number of characters in the input argument.

```typescript
returns len("Hello"); // returns 5
```

### urlEncode

**Signature:** urlEncode(**self** input: text) -> text

Returns the input argument in [URL Encoding](https://www.w3schools.com/tags/ref_urlencode.ASP).

```typescript
// returns "https%3a%2f%2fwww.novacura.com"
return URLEncode("https://www.novacura.com")
```

### urlDecode

**Signature:** urlDecode(**self** input: text) -> text&#x20;

Converts the input argument from [URL Encoding](https://www.w3schools.com/tags/ref_urlencode.ASP) into regular text.

```typescript
return "https%3a%2f%2fwww.novacura.com".urlDecode() 
// returns https://www.novacura.com
```

### chr

**Signature:** chr(input: primitive) -> text&#x20;

Converts a unicode code point (in decimal format) to the corresponding text value. Inputs must be in the Basic Multilingual Plane of Unicode, otherwise the function will raise an error.

```typescript
let tabCharacter = chr(9); // the tab character
let blackPointingUpTriangle = chr(9650); // "▲" 
```

### left

**Signature:** left(**self** input: text, count: number) -> text&#x20;

Returns a specified number of characters taken from the input text, starting from the left. If the number of characters specified by the `count` argument exceeds the number of characters in the input, the whole of input will be returned. If `count` is zero or less then an empty text will be returned.

```typescript
let oneFromTheLeft = left("hello", 1) // oneFromTheLeft == "h"
let largerThanInput = left("hello", 100) // largerThanInput = "hello" 
let zeroFromLeft = "hello".left(0) // zeroFromLeft == ""
```

### right

**Signature:** right(**self** input: text, count: number) -> text&#x20;

Returns a specified number of characters taken from the input text, starting from the right. If the number of characters specified by the `count` argument exceeds the number of characters in the input, the whole of input will be returned. If the `count` is zero or less then an empty text will be returned.

```typescript
let threeFromRight = right("hello", 3) // threeFromRight == "llo"
let largerThanInput = "hello".right(500) // largerThanInput = "hello" 
let zeroFromRight = right("hello", 0) // zeroFromRight == ""
```

### mid

**Signature:** mid(**self** input: text, index: number, count: number) -> text&#x20;

Returns a specified number of characters taken from the input text, starting at the position indicated by the `index`argument.&#x20;

If the numbers of the characters specified by the `count` argument exceeds the remaining characters after the index, the rest of the text will be returned.&#x20;

The function will throw an error if the given start index is greater than or equal to the number of characters in the input.

```typescript
return "hello".mid(1,3) // will return "ell"
```

### regexMatch

**Signature:** regexMatch(input: text, pattern: text) -> boolean

Returns a boolean value indicating whether if the given [Regular Expression](https://learn.microsoft.com/en-us/dotnet/standard/base-types/regular-expression-language-quick-reference) pattern can be match in the input text.

```typescript
let contains3LetterWord = regexMatch("abc", @"\w{3}") // true
let contains3Digits = regexMatch("abc", @"\d{3}") //  false
```

### regexMatches

**Signature:** regexMatches(input: text, pattern: text) -> text\*&#x20;

Returns a sequence of matches, if any, for the [Regular Expression](https://learn.microsoft.com/en-us/dotnet/standard/base-types/regular-expression-language-quick-reference) pattern in the input text.

```typescript
let twoDigits = regexMatches("123 45", @"\d{2}") // twoDigits == ["12", "45"]
let fourDigits = regexMatches("123 45", @"\d{4}") // fourDigits == []
```

### regexReplace

**Signature:** regexReplace(**self** input: text, pattern: text, replacement: text ) -> text&#x20;

Replaces the matches of the given [Regular Expression](https://learn.microsoft.com/en-us/dotnet/standard/base-types/regular-expression-language-quick-reference) pattern with the replacement argument in the input text. If nothing in the input matches the pattern, the original input will be returned.

```typescript
let digitsAsX = regexReplace("2hello1", @"\d", "x") // digitsAsX == "xhellox"
let noDigits = "2hello1".regexReplace(@"\d", "") // noDigits == "hello"
```

### replace

**Signature:** replace(**self** input: text, search: text, replacement: text ) -> text&#x20;

Returns a value in which all occurrences of `search`in `input` are replaced with `replacement`.

```typescript
return Replace("one two three", "three", "four") // returns "one two four"
```

### trim

**Signature:** trim(**self** input: text) -> text&#x20;

Returns the input text with trailing and leading whitespace removed.

```typescript
return "   hello space ".trim() // returns "hello space"
```

### inStr

**Signature:** inStr(**self** source: text,  lookFor: text) -> number

Returns the index of the first occurrence of the `lookFor` argument in the `source` text. If no occurrence exists inside the `source` text, the function returns -1.

```typescript
return inStr("hello world!", "w") // returns 6
```

### guid

**Signature:** guid() -> text&#x20;

Creates a non-empty UUID  as described in [RFC 4122, Sec. 4.4](https://datatracker.ietf.org/doc/html/rfc4122#section-4.4).

```typescript
return guid();
```

### str

**Signature:** str(input: any) -> text&#x20;

Returns a text representation of the input. Null values will be converted to a empty text value.

```typescript
let example1 = str({name: "bob", id: 33}); // "{name: 'bob', id: 33}"
let example2 = str([1,2,3]); // "[1, 2, 3]"
let example3 = str(2 * 3); // "6"
```

### rgb

**Signature:** rgb(red: number, green: number, blue: number) -> text&#x20;

Returns the hex code corresponding the RGB color with given values of `red`, `green` and `blue`. The arguments will be rounded to the nearest integer in the range of 0 through 255.&#x20;

```typescript
return rgb(255, 255, 255); // will return #FFFFFF 
```

### split

**Signature:** split(**self** input: text, delimiter: text ) -> text\*&#x20;

Returns all sub strings of the input argument, separated by the specified `delimiter.`If the given delimiter is not present in the input text then a sequence consisting only of the input text will be returned.

The delimiter argument must be exactly one character long.

```typescript
return "1/2/3".split('/') // returns ["1", "2", "3"]
```

### splitToTable

**Signature:** splitToTable(**self** input: text, delimiter: text ) -> {value: text}\*&#x20;

A version of the split function designed for compatiblity with Flow Classic.

```typescript
return "1/2".splitToTable('/') // returns [{value: "1"}, {value: "2"}]
```

### join

**Signature:** join(**self** sequence: primitive\*, separator: text ) -> text&#x20;

Concatenates all the text values in the `sequence` argument and returns a single text, inserting the `separator` between each element.

```typescript
return ["a","b","c","d"].join(" ") // returns "a b c d"
```

```typescript
return [1,2,3,4].join(",") // returns "1,2,3,4"
```

### format

**Signature:** format(input: primitive, pattern: text) -> text&#x20;

Returns a formatted text representation of a given number or datetime input using the given `pattern` to format it.

#### For numbers

Valid `pattern` argument for numbers are the same as standard format specifiers provided by [.NET](https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings) to format numbers for decimal values.  &#x20;

```typescript
return format(0.5, 'p') // will return "50%"
```

#### For dates

Valid `pattern` argument for numbers are the same as standard format specifiers provided by [.NET](https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-date-and-time-format-strings) to format dates.&#x20;

<pre class="language-typescript"><code class="lang-typescript"><strong>let d = date("2024-02-08T14:12:34.6821542+01:00");
</strong>return format(d, "yyyy-mm-dd") // will return "2024-02-08"
</code></pre>

### formatLocale

**Signature:** formatLocale(input: primitive, pattern: text, locale: text) -> text&#x20;

Returns a formatted text representation of a given number or datetime input using the given pattern and locale to format it.

The `locale` argument corresponds to a langue code as described in [BCP 47](https://tools.ietf.org/html/bcp47). If the locale argument is the empty text, the formatLocale function works the same as the format function.

#### For numbers

Valid pattern argument for numbers are the same as standard format specifiers provided by [.NET](https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings) to format numbers.  &#x20;

```typescript
return formatLocale(1000, 'C', 'en-US') // will return "$1,000.00"
```

#### For dates

Valid pattern argument for numbers are the same as standard format specifiers provided by [.NET](https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-date-and-time-format-strings) to format dates.&#x20;

<pre class="language-typescript"><code class="lang-typescript"><strong>let d = date("2024-02-08T14:12:34.6821542+01:00");
</strong>return formatLocale(d, "yyyy-mm-dddd", "fr-FR")  // will return "2024-04-jeudi" 
</code></pre>

## Binary-related functions

### encodeText

**Signature:** encodeText(**self** input: text, encoding: text) -> binary

Encodes the input text to binary value with the given encoding. Valid values for the `encoding` parameter are: `iso-8859-1`, `utf-8`, `utf-16` and `utf-32`.

```typescript
return encodeText('åäö', 'iso-8859-1')
```

### decodeText

**Signature:** decodeText(**self** data: binary, encoding: text) -> binary

Converts a binary value into a text representation using the provided encoding. Valid values for the `encoding` parameter are: `iso-8859-1`, `utf-8`, `utf-16` and `utf-32`.

```typescript
let result = encodeText('åäö', 'iso-8859-1');
return decodeText(result, 'iso-8859-1') // returns "åäö"
```

### base64Encode

**Signature:** base64Encode(**self** data: binary) -> text

Converts a binary value into its [Base 64](https://en.wikipedia.org/wiki/Base64) text representation.

```typescript
let result = base64Decode("hello world"):
return base64Encode(result) // returns "hello world"
```

### base64Decode

**Signature:** base64Decode(**self** base64: text) -> binary

Converts a base64 encoded text into a binary file.

<pre class="language-typescript"><code class="lang-typescript"><strong>return decodeText(base64Decode('aGFsbMOlIHbDpHJsZGVu'), 'utf-8') 
</strong><strong>// returns "hallå världen"
</strong></code></pre>

## Null-related functions

### isNull

**Signature:** isNull\<T>(value: T?, replacement:  T) -> T

Returns `value` if is not null, otherwise returns the `replacement` argument.

```typescript
let nbrOrFive = isNull(3, 5) // nbrOrFive == 3

let test: text? = null;
let testOrHello = isNull(test, "hello") // testOrHello == "hello" 
```

### isNullOrEmpty

**Signature:** isNullOrEmpty(value: text?, replacement: text) -> text

Returns `value` if it is not equal to null or the empty string (""); otherwise returns the `replacement` argument.

```typescript
let x = isNullOrEmpty("", "hello"); // x == "hello"
let y = isNullOrEmpty("hello", "goodbye"); // y == "hello"
let z = isNullOrEmpty(null, "hi"); // z == 'hi'
```

## Number-related functions

### ceil

**Signature:** ceil(input: number) -> number

Rounds `input` argument upward to the nearest integer.

```typescript
let positiveResult = ceil(5.5) // positiveResult == 6
let negativeResult = ceil(-5.5) // negativeResult == -5
```

### floor

**Signature:** floor(input: number) -> number

Rounds `input`downward to the nearest integer.

```typescript
let positiveResult = floor(5.5) // positiveResult == 5
let negativeResult = floor(-5.5) // negativeResult == -6
```

### random

**Signature:** random(min: number, max:number) -> number

Generates a pseudo-random number between `min` and `max`.

```typescript
return random(0,5) // result will be a number between 0 to 5
```

### max

**Signature:** max(a: number,  b:number) -> number

Returns the greatest of `a` and `b`.

```typescript
let result = max(2,3) // result == 3
```

### min

**Signature:** min(a: number,  b:number) -> number

Returns the least or `a` and `b`.

```typescript
let result = max(2,3) // result == 2
```

### pow

**Signature:** pow(base: number,  exponent: number) -> number

Returns the `base` raised to the `exponent`.

```typescript
return pow(2,3) // returns 8
```

### round

**Signature:** round(x: number) -> number

Returns `x` rounded to the nearest integer.

```typescript
return round(1.2) // returns 1
```

### sum

**Signature:** sum(sequence: number?\*) -> number

Returns the sum of the numbers in a sequence. Returns 0 if the sequence is empty. Null values count as zero.

```typescript
return sum([1, 2, 3, null, 4, 5]) // returns 15
```

## Date-related functions

See also the [DateTime module.](/flow-connect/reference/reference/flowscript/walkthrough/datetime-module.md)

### now

**Signature:** now() -> datetime

Returns a datetime value containing the calendar date and time indicated by the system clock of device on which the FlowScript is running.

```typescript
let currentDateAndTime = now();
```

### date

**Signature:** date(input: text) -> datetime

Converts the input argument to a datetime if possible. If the input cannot be converted to a date, the function raises an error.

The date function supports several different date and time formats such as YYYY-MM-DD, ISO 8601 and more.

```typescript
let d = date("2024-02-08T14:12:34.6821542+01:00");
```

### toDate

**Signature:** toDate(input: text, format: text) -> datetime

Converts the input argument to a datetime with the given format if possible. if the input cannot be converted to a date using the specified format, the function raises an error.

```typescript
let yearMonthDay = ToDate('2021-03-10', 'yyyy-MM-dd')
let monthDayYear = ToDate('03/10/2021', 'MM/dd/yyyy')

// Here both yearMonthDay and monthDayYear will return the same date which
// will be the 10th of mars 2021 
```

## Sequence-related functions &#x20;

See also the [Seq module](/flow-connect/reference/reference/flowscript/walkthrough/seq-module.md).

### any

**Signature:** any(**self** sequence: unknown\*) -> boolean

Returns a boolean value indicating whether the sequence has at least one element.

```typescript
let someItems = [1, 2];
let noItems = [];

let a1 = any(someItems); // true
let a2 = noItems.any(); // false
```

### count

**Signature:** count(**self** sequence: unknown\*) -> number

Returns the number of items in a sequence.

```typescript
let xs = [1, 2, 3];

let c1 = count(xs);
let c2 = xs.count();
```

### first

**Signature:** first\<T>(**self** sequence: T\*) -> T

Returns the first element from the sequence, or raises an error if the sequence is empty.

```typescript
let xs = [1, 2];
return xs.first(); // returns 1
```

### firstOrDefault

**Signature:** firstOrDefault\<T>(**self** sequence: T\*, defaultValue: T) -> T

Returns the first element from the sequence. If the seauence is empty, the function returns the `defaultValue` argument.

```typescript
let xs = case when random(0, 1) > 0.5
              then []
              else [1, 2, 3]
              end;

return xs.firstOrDefault(0)
```

### firstOrNull

**Signature:** firstOrNull\<T>(**self** sequence: T\*) -> T?

Returns the first element from the sequence. If the seauence is empty, the function returns null.

```typescript
return [1,2,3].firstOrNull() // will return 1
```

```typescript
return firstOrNull([]) // will return null
```

### last

**Signature:** last\<T>(**self** sequence: T\*) -> T

Returns the last  element from the sequence, or raises an error if the sequence is empty.

```typescript
return [1,2,3].last() // will return 3
```

### lastOrDefault

**Signature:** lastOrDefault\<T>(**self** sequence: T\*, default: T ) -> T

Returns the last  element from the sequence, or the `default` argument if the sequence is empty.

```typescript
return [].lastOrDefault(22) // will return 22
```

### lastOrNull

**Signature:** lastOrNull\<T>(**self** sequence: T\*, default: T ) -> T?

Returns the last  element from the sequence, or null if the sequence is empty.

```typescript
return [].lastOrNull() // return null
```

### range

**Signature:** range(start: number, count: number) -> number\*

Returns a sequence of `count`integers beginning with `start`.

```typescript
return range(5,3) // return [5,6,7]
```

### take

**Signature:** take\<T>(**self** sequence: T\*,  count: number ) -> T\*

Returns the first N elements of the sequence.

```typescript
return [1,2,3,4,5,6].take(3) // returns [1,2,3]
```

### skip

**Signature:** skip\<T>(**self** sequence: T\*,  count: number ) -> T\*

Returns a sequence where the first N elements are skipped.

```typescript
return [1,2,3,4,5,6].skip(3) // returns [4,5,6]
```

### eval

**Signature:** eval\<T>(**self** sequence: T\*) -> T\*

Materializes a lazy sequence. See also [A note on laziness.](/flow-connect/reference/reference/flowscript/walkthrough/queries.md#advanced-a-note-on-laziness)

```typescript
let nbrs = select random(0, 10) as r from range(0, 10);

let nbrsFiltered = nbrs where r != 2;
let nbrsFilteredOnceMore = nbrs where r != 2;

return nbrsFiltered == nbrsFilteredOnceMore // will likely return false
```

```typescript
let nbrs = eval(select random(0, 10) as r from range(0, 10));

let nbrsFiltered = nbrs where r != 2;
let nbrsFilteredOnceMore = nbrs where r != 2;

return nbrsFiltered == nbrsFilteredOnceMore // will always return true
```

### flatten

**Signature:** flatten\<T>(**self** sequence: T\*\*) -> T\*

Flattens a sequence-of-sequences into a single sequence.

```typescript
return [[1,2,3],[4,5,6],[7,8,9]].flatten() // returns [1,2,3,4,5,6,7,8,9]
```

### empty

**Signature:** empty\<T>(**self** sequence: T\*) -> T\*

Returns an empty sequence with the same type as the given argument. This function only exists for reasons of Flow Classic compatiblity.

```typescript
return [1, 2, 3, 4].empty() // returns []
```

## Miscellaneous

### hash

**Signature:** hash(value: any) -> number

Returns a numeric hash of the value.

<pre class="language-typescript"><code class="lang-typescript"><strong>return hash([1, 2, 3, 4]) // will return 1644472305
</strong></code></pre>

### identity

**Signature:** identity\<T>(x: T) -> T

Returns the `x` argument. If the type argument is explicitly written out, the function can be used to "upcast" values to the primitive type.

```typescript
return identity<primitive>(1) // will return 1 as a primtive value
```

### sleep

**Signature:** sleep(minMilliseconds: number, maxMilliseconds: number) -> number

Pauses script execution for a randomly chosen number of milliseconds between `minMilliseconds`and `maxMilliseconds`.

```typescript
return sleep(10000, 10000) // will return 10000 and pause the execution for 1 sec
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.novacura.com/flow-connect/reference/reference/flowscript/walkthrough/built-in-functions.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
