# Create and Call Functions

## Introduction

**Functions** are methods you build yourself and are comparable to JavaScript functions. They are a set of statements that perform a task or calculate a value and are useful to combine some functionality that you use multiple times in your ruleset. For example, let's assume that the travel insurance calculator needs to add extra costs depending on age that applies to both insurance and extra costs:

| Age category | Extra costs per day |
| ------------ | ------------------- |
| 18 - 30      | 0.15                |
| 31 - 50      | 0.10                |
| 51 and older | 0.05                |

You can wrap this up in an expression like this:

```javascript
let extraCosts = 0;
if (Age >= 18 && Age < 31) {
    extraCosts = ROUND(NumberOfDays * ExtraCostPerDay18_30);
}
if (Age >= 31 && Age < 51) {
    extraCosts = ROUND(NumberOfDays * ExtraCostPerDay31_50);
}
if (Age >= 51) {
    extraCosts = ROUND(NumberOfDays * ExtraCostPerDay51AndUp);
}
```

And add this to both rules in `Travel insurance calculator` so that they use the `extraCosts` variable in their calculation.&#x20;

But this has a major downside: if something changes to the age categories, you have to modify every rule where this code is used. In that case, it's better to create a function that calculates the extra costs, which you can (re)use from anywhere in your ruleset. If then something changes to the age categories, you only have to modify the function.

By the end of this tutorial, you'll know how to:

* Create a function.
* Call a function from a rule.

## Create and call functions

### Task: Add extra input and constants

Start with creating the following input and constants in your `Travel insurance calculator` ruleset:

#### Input

<table><thead><tr><th width="298">Name</th><th>Type</th></tr></thead><tbody><tr><td><code>DateOfBirth</code></td><td><code>date</code></td></tr></tbody></table>

#### Constants

<table><thead><tr><th width="298">Name</th><th>Constant type</th><th>Value</th></tr></thead><tbody><tr><td><code>ExtraCostPerDay18_30</code></td><td><code>Simple</code></td><td><code>0.15</code></td></tr><tr><td><code>ExtraCostPerDay31_50</code></td><td><code>Simple</code></td><td><code>0.10</code></td></tr><tr><td><code>ExtraCostPerDay51AndUp</code></td><td><code>Simple</code></td><td><code>0.05</code></td></tr></tbody></table>

### Task: Create a function to calculate extra costs

Like methods, functions need input to operate on, and an input for a function is called a parameter. So when calling a function, you supply its parameters, and the function returns a calculated or determined result.

1. Create a function named `AgeSurcharge`, and in the **Return type** list, select `number`.
2. Click **Add parameter**.\
   ↳ Rulecube adds a parameter row:<br>

   <figure><img src="https://content.gitbook.com/content/kPoC1P5CqaOhS6k4bIDl/blobs/WKlFVerJlLBDJ7NkmEXC/image.png" alt=""><figcaption></figcaption></figure>
3. In the **Name** field, enter `age`, and in the **Type** list, select `number`.
4. Add a second parameter named `numberOfDays`, and set its **Type** to `number`.
5. In the **Function body**, copy and paste the following function:<br>

   <pre class="language-javascript" data-line-numbers><code class="lang-javascript">if (age >= 18 &#x26;&#x26; age &#x3C; 31) {
       return numberOfDays * ExtraCostPerDay18_30;
   }
   if (age >= 31 &#x26;&#x26; age &#x3C; 51) {
       return numberOfDays * ExtraCostPerDay31_50;
   }
   if (age >= 51) {
       return numberOfDays * ExtraCostPerDay51AndUp;
   }
   return 0;
   </code></pre>

   \
   **Explanation:** Lines 1, 4 and 7 check the `age` parameter and lines 2, 5 and 8 calculate and `return` the result using the correct constant.\
   \
   **IMPORTANT**: Do not worry about the code if you do not fully understand it right now, in the next lesson we will replace this with a better and easier to understand solution!<br>
6. Click **Save**.\
   ↳ The function is ready for calling now.

{% hint style="info" %}
If you prefer keyboard shortcuts, press `Ctrl+S` for saving.
{% endhint %}

### Task: Add an Age rule

To prevent us from repeating ourselves, let's first create a rule that pre-calculates the current age based on the `DateOfBirth` input.

1. Add a new rule named `Age` with the following expression:<br>

   ```
   AGE(DateOfBirth)
   ```
2. Disable the "**Output**" checkbox

### Task: Call the `AgeSurcharge` function within your ruleset

1. Open the `InsuranceCosts` rule.

2. Change the expression to this code:<br>

   ```javascript
   ROUND(RiskCostsPerDay.get(RiskCategory) * NumberOfDays + AgeSurcharge(Age, NumberOfDays))
   ```

3. Now change the expression for the `ElectronicDeviceCosts` rule to this code:<br>

   ```javascript
   ROUND(NumberOfDays * NumberOfItems * CostsPerItemPerDay + AgeSurcharge(Age, NumberOfDays))
   ```

4. Save your ruleset and try it out in the sandbox.

{% hint style="info" %}
You can save the input values you enter on the *Sandbox* page to reuse them in later try out sessions, which saves you time:

1. Enter the input values.
2. Click **Save as**.\
   ↳ The *Save input* pop-up opens.
3. In the **Name** field, enter name for the input set.
4. Click **OK**.<br>

In a later try-out session, in the **Input** list, select the name of the stored input set, and the stored values are filled into the corresponding input fields.
{% endhint %}

## Recap

You've created functions that further sophisticate your rulesets and accelerate your development cycle.

## What's next?

So far, you've worked with separated input, constants, and rules. But Rulecube has the **entities** component in which input, constants, and rules can be combined. This improves the manageability of your rulesets and is the most natural/logical way to implement a business rule in a ruleset.
