CQL allows you to define your own functions to perform custom operations and improve the maintainability of your queries.
Functions enable you to encapsulate complex logic, avoid repeating code, and make queries more readable and easier to understand.
If you try to declare parameters with the same name as a variable, you will get an error because variables cannot be redefined.
Here is an example of a function that takes multiple parameters:
let price = (value, discount) => value - (value * discount);price(100, 0.1) // 90
For single-parameter functions, you can omit the parentheses around the parameter list:
let welcome = subject => "Hello, " & subject & "!";welcome("world") // Hello, world!
You can also define parameterless functions:
let welcome = () => "Hello, " & location's city & "!";welcome() // Hello, <Countru>!
Because the body expression has access to variables defined in the parent context, you can access the user's location without having to pass it as a parameter.
Function calls allow you to invoke functions with specific inputs, known as arguments. CQL supports different ways to pass arguments to functions, as described below.
If a function does not take any parameters, you can just call it without any arguments:
let hello = () => "Hello, world!";hello() // "Hello, world!"
Note that calling a function with arguments when it does not expect any will work, but the arguments will be ignored. However, attempting to call a function without passing the required arguments will result in an error.
Positional arguments refer to the practice of passing arguments to a function in the same order as they appear in the function definition.
Suppose you have a function that takes three parameters:
let calculate = (a, b, c) => a + b * c;calculate(1, 2, 3) // 7
In the example above, the parameters a, b, and c receive the values 1, 2, and 3, respectively.
You can also call functions with arguments specified by their names, in which case the order does not matter.
In the example below, we provide named arguments when calling the calculate function:
let calculate = (a, b, c) => a + b * c;calculate(c: 3, b: 2, a: 1) // 7
It's also possible to mix both positional and named arguments in a function call — as long as all positional arguments are provided before the named arguments.
Although you can use both positional and named arguments in a function call, it is best to stick to one type to avoid confusion.
Here is an example of a function call using both argument types:
let calculate = (a, b, c) => a + b * c;calculate(1, c: 3, b: 2) // 7