> For the complete documentation index, see [llms.txt](https://docs.eximee.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.eximee.com/documentation/documentation-en/budowanie-aplikacji/logika-biznesowa/scriptcode/materialy-dodatkowe/sciaga-fragmenty-kodow-js.md).

# Cheat sheet - JS code snippets

The code snippets below present example ways to implement commonly used operations in **ScriptCode**. These are simplified patterns that you should adapt yourself to the specific use case, including parameter names, artifact type, expected output format, and required business logic.

## Checking for duplicates in an array

### Method 1

Used to clean data. Iterates through the array and returns a new one with duplicates removed.

```js
function distinct(array) {
  const a = [];
  for (let i = 0, l = array.length; i < l; i++) {
    if (a.indexOf(array[i]) === -1) a.push(array[i]);
  }
  return a;
}
```

### Method 2

Intended for validation only. Returns only the boolean value true or false. Asks: "Are there any duplicates in this list?". Does not return cleaned data.

```js
function hasDuplicates(array) {
  const valuesSoFar = Object.create(null);
  for (let i = 0; i < array.length; i++) {
    const value = array[i];
    if (value in valuesSoFar) return true;
    valuesSoFar[value] = true;
  }
  return false;
}
```

***

## Removing empty values from an array

```js
const newArr = arr.filter((el) => !!el);
```

***

## Checking for duplicates in a JSON object

```js
const listOfGroupsWithoutDuplicates = listOfGroups.filter(
  (thing, index, self) =>
    index ===
    self.findIndex((t) => JSON.stringify(t) === JSON.stringify(thing)),
);
```

***

## Checking whether an array contains an element

### Method 1

```js
if (arr.indexOf(element) !== -1) {
  return [{ output: "true" }];
} else {
  return [{ output: "false" }];
}
```

### Method 2

```js
return [{ output: arr.includes(element) ? "true" : "false" }];
```

***

## Extracting data from a timestamp

```js
const dateOfBirth = context.getFirstParameter("dataUrodzenia");
let date = parseInt(dateOfBirth);
date = new Date(date);
const year = date.getFullYear();
const month = date.getMonth() + 1;
const day = date.getDate();
```

***

## Getting today's date

```js
const dateNow = new Date();
const today = `${dateNow.getFullYear()}-${(dateNow.getMonth() + 1)
  .toString()
  .padStart(2, "0")}-${dateNow.getDate().toString().padStart(2, "0")}`;
```

***

## Extracting file names from the UploadFile component

```js
const names = JSON.parse(context.getFirstParameter("zalaczniki"));
const namesList = names.toString();
```

***

## Getting the value of a specific component attribute

```js
const names = context.getData("@GesUploadFile1", "fileNames");
const sizes = context.getData("@GesUploadFile1", "totalFilesSize");
```

***

## Removing spaces

```js
let value = context.getFirstParameter("value");
value = value.replace(/\s+/g, "");
```

***

## Matching a value to a mask (regex)

```js
const input = context.getFirstParameter("dokumentTozsamosci");
const regex = /^[a-zA-Z]{3}[0-9]{6}$/;

if (!input.match(regex)) {
  Logger.info("Invalid identity card number");
} else {
  return [];
}
```

***

## Counting occurrences of a given value

### Method 1

```js
const input = context.getParameters("input");
let trueOccurences = 0;

for (let i = 0; i < input.size(); i++) {
  if (input.get(i) === "true") {
    trueOccurences++;
  }
}
```

### Method 2

```js
const input = context.getParameters("input").toArray();
const trueOccurrences = input.filter((val) => val === "true").length;
```

***

## Checking how many full years have passed

```js
let dateOfBirth = context.getFirstParameter("dataUrodzenia");

if (dateOfBirth !== "" && dateOfBirth !== null) {
  let date = parseInt(dateOfBirth);
  dateOfBirth = new Date(date);
  dateOfBirth.setHours(12, 0, 0, 0);

  const todayDate = new Date();
  todayDate.setHours(12, 0, 0, 0);
  const difference = todayDate.getTime() - dateOfBirth.getTime();
  const ageDate = new Date(difference);

  if (Math.abs(ageDate.getUTCFullYear() - 1970) >= 18) {
    Logger.info("At least 18 years have passed");
  } else {
    Logger.info("18 years have not passed");
  }
} else {
  return [];
}
```

***

## Getting data from a repeatable section

```js
const citizenshipList = [];
const maritalStatusList = [];
const documentTypeList = [];

let index = 0;
while (index < 30) {
  const rowPrefix =
    "GesComplexComponent2.GesComplexComponent3.GesRepeatableSection2.row" +
    index +
    ".GesComplexComponent2.GesComplexComponent3.GesComplexComponent1.";

  const isRowVisible = context.isVisible(rowPrefix + "GesCombobox2");

  if (isRowVisible) {
    const citizenship = context.getData(rowPrefix + "GesCombobox2", "label");
    const maritalStatus = context.getData(rowPrefix + "GesCombobox3", "label");
    const documentType = context.getData(rowPrefix + "GesCombobox4", "label");

    citizenshipList.push(citizenship);
    maritalStatusList.push(maritalStatus);
    documentTypeList.push(documentType);
  }

  index++;
}
```

***

## ServiceProxy call

```js
const input = context.getInputParameters();
const response = context.callService(
  "Plus500ZusAdditionalValueServiceProxy",
  input,
);
const result = response.get(0).get("result");
const parsedResult = JSON.parse(result);
```

***

## Creating a dictionary

### Method 1

```js
const items = {
  "Identity card": "DO",
  "Polish passport": "PP",
  "Foreign passport": "PZ",
};

function DictElement(label, value) {
  this.label = label;
  this.value = value;
}

const dict = [];
for (const item in items) {
  dict.push(new DictElement(item, items[item]));
}
return dict;
```

### Method 2

```js
const items = {
  "Identity card": "DO",
  "Polish passport": "PP",
  "Foreign passport": "PZ",
};

const dict = Object.keys(items).map((klucz) => ({
  label: klucz,
  value: items[klucz],
}));

return dict;
```

***

## Formatting floating-point numbers

```js
function format(interest) {
  return parseFloat(interest)
    .toFixed(2)
    .replace(".", ",")
    .replace(/(?!^)(?=(?:\d{3})+(?:,|$))/gm, " ");
}
```

***

## Returning the day/month/year suffix

```js
function formatDate(unit, quantity) {
  let literal = "dni";

  if (unit === "DAY") {
    literal = quantity === 1 ? "dzień" : "dni";
  }

  if (unit === "MONTH") {
    if (quantity === 1) {
      literal = "miesiąc";
    } else if (
      quantity < 5 ||
      (quantity > 20 && ["2", "3", "4"].includes(String(quantity).slice(-1)))
    ) {
      literal = "miesiące";
    } else {
      literal = "miesięcy";
    }
  }

  if (unit === "YEAR") {
    if (quantity === 1) {
      literal = "rok";
    } else if (
      quantity < 5 ||
      (quantity > 20 && ["2", "3", "4"].includes(String(quantity).slice(-1)))
    ) {
      literal = "lata";
    } else {
      literal = "lat";
    }
  }

  return literal;
}
```

***

## Creating an array from a list of objects

```js
const schemesList = schemesListWithoutDuplicates.map((a) => a.schemaId);
```

***

## Filtering an array

```js
function callService(context) {
  let data =
    '[{"name":"Jan","lastname":"Kowalski","role":"admin"},{"name":"Adam","lastname":"Pietrzak","role":"user"},{"name":"Karol","lastname":"Kowalski","role":"admin"},{"name":"Joanna","lastname":"Wieczorek","role":"user"}]';
  data = JSON.parse(data);
  data = data.filter((element) => element.role === "user");
  return [{ selectedUsersFullListEnd: JSON.stringify(data) }];
}
```

***

## Removing selected object parameters

### Method 1

```js
function callService(context) {
  let data =
    '[{"name":"Jan","lastname":"Kowalski","role":"admin"},{"name":"Adam","lastname":"Pietrzak","role":"user"},{"name":"Karol","lastname":"Kowalski","role":"admin"},{"name":"Joanna","lastname":"Wieczorek","role":"user"}]';
  data = JSON.parse(data);
  data = data.map((element) => {
    delete element.role;
    return element;
  });
  return [{ selectedUsersFullListEnd: JSON.stringify(data) }];
}
```

### Method 2

```js
function callService(context) {
  let data =
    '[{"name":"Jan","lastname":"Kowalski","role":"admin"},{"name":"Adam","lastname":"Pietrzak","role":"user"},{"name":"Karol","lastname":"Kowalski","role":"admin"},{"name":"Joanna","lastname":"Wieczorek","role":"user"}]';
  data = JSON.parse(data);
  for (const element of data) {
    delete element.role;
  }
  return [{ selectedUsersFullListEnd: JSON.stringify(data) }];
}
```

## Removing duplicates from an array using `Set`

```js
// Values to array
const accountPermissionArr = accountPermissionInput.toArray();

// Set removes duplicates (in JS it preserves insertion order)
const accountPermissionSet = new Set(accountPermissionArr);

// Transform the Set object back into an array
const accountPermissionFinal = Array.from(accountPermissionSet);

// (optional) if you want to sort the result alphabetically:
// const accountPermissionFinal = Array.from(accountPermissionSet).sort();
```

***

## Getting values using `inputParameters`

```js
function getSingleValue(valuesMap, paramName, defaultValue) {
  const values = valuesMap.get(paramName);
  if (values != null && !values.isEmpty() && values.get(0) != null) {
    if (values.size() > 1) {
      throw new Error(paramName + " must have single value");
    } else {
      return values.get(0);
    }
  } else {
    return defaultValue;
  }
}

function getBooleanValue(valuesMap, paramName, defaultValue) {
  const value = getSingleValue(valuesMap, paramName, defaultValue);
  return value === true || value === "1" || value === "true";
}

// Usage
const inputParameters = context.getInputParameters();
const onlyVATAccounts = getBooleanValue(
  inputParameters,
  "inputOptionalOnlyVATAccounts",
  false,
);
const companyNik = getSingleValue(
  inputParameters,
  "inputOptionalCompanyNik",
  null,
);
```

***

## Creating a BigDecimal and useful add-ons

```js
const bigDecimalZero = BigDecimal.valueOf("0").bigDecimal;

function createBigDecimal(value, locale) {
  if (!value) {
    return value;
  }

  let formatValue;

  if (locale === "en") {
    formatValue = value.toString().replace(/,/g, "");
  } else if (locale === "es") {
    formatValue = value.toString().replace(/\./g, "").replace(/,/g, ".");
  } else {
    // default: remove whitespace and replace comma with a dot
    formatValue = value.toString().replace(/\s+/g, "").replace(",", ".");
  }

  return BigDecimal.valueOf(formatValue).bigDecimal;
}

function createBigDecimalOrZero(value, locale) {
  return !value ? bigDecimalZero : createBigDecimal(value, locale);
}

function createBigDecimalOrNull(value, locale) {
  return !value ? null : createBigDecimal(value, locale);
}
```

***

## Formatting account balance

```js
const UNBREAKABLE_SPACE = "\u00A0";

function formatAmount(number, locale) {
  const GROUPING_SIZE_OF_BALANCE = 3;
  const NUMBER_OF_FRACTION_DIGITS_IN_BALANCE = 2;

  const localeSettings = {
    en: { groupingSeparator: ",", decimalSeparator: "." },
    pl: { groupingSeparator: UNBREAKABLE_SPACE, decimalSeparator: "," },
    es: { groupingSeparator: ".", decimalSeparator: "," },
  };

  // allow 0, reject null/undefined
  if (number === null || number === undefined) {
    return "";
  }

  const settings = localeSettings[locale] || localeSettings.pl;

  const roundedNumber = Number(number).toFixed(
    NUMBER_OF_FRACTION_DIGITS_IN_BALANCE,
  );

  const parts = roundedNumber.split(".");
  let integerPart = parts[0];
  const decimalPart = parts[1];

  const regex = new RegExp(
    `\\B(?=(\\d{${GROUPING_SIZE_OF_BALANCE}})+(?!\\d))`,
    "g",
  );
  integerPart = integerPart.replace(regex, settings.groupingSeparator);

  return integerPart + settings.decimalSeparator + decimalPart;
}

function getAccountBalanceFormatted(loan, locale) {
  return (
    formatAmount(loan.availableFunds, locale) +
    UNBREAKABLE_SPACE +
    loan.currencyCode
  );
}
// Returns e.g.: "79 561,00 PLN" (PL) or "79,561.00 USD" (EN)

function formatAmountNeutral(value) {
  const formatNeutral = DecimalFormat.of("0.00", DecimalFormatSymbols.EN);
  return value !== null && value !== undefined
    ? formatNeutral.format(BigDecimal.valueOf(value.toString()))
    : "";
}
// Returns neutral format (EN) e.g.: "79561.00"
```

***

## Creating and throwing a business error

```js
function throwBusinessError(textcontentName, errorDescription) {
  const builder = context.getErrorPageDefinitionBuilder();
  builder.bodyTextContent(textcontentName);
  builder.msg(errorDescription);
  context.throwBusinessException(builder);
}

// Example of throwing an error:
const pesel = context.getFirstParameter("pesel");

if (isInputEmpty(pesel)) {
  throwBusinessError(
    "error_page_default-*",
    "Failed to retrieve customer data.",
  );
}
```

***

## Using the spread operator `...`

### Method 1

Example of extending customer data.

```js
function callService(context) {
    const customerData = JSON.parse(
        '{"name":"Adam","lastname":"Pietrzak","role":"user"}'
    );

    const updatedCustomerData = {
        ...customerData,
        verificationStatus: "POSITIVE",
        verificationDate: new Date().toISOString()
    };

    return [{
        'updatedCustomerData': JSON.stringify(updatedCustomerData)
    }];
}
```

Output:

```js
{
  "name": "Adam",
  "lastname": "Pietrzak",
  "role": "user",
  "verificationStatus": "POSITIVE",
  "verificationDate": "2026-07-15T08:45:12.123Z"
}
```

### Method 2

Example of combining two lists into one.

```js
const userAttachments = JSON.parse(context.getFirstParameter("userAttachments"));
const generatedAttachments = JSON.parse(context.getFirstParameter("generatedAttachments"));

const allAttachments = [
  ...userAttachments,
  ...generatedAttachments
];
```

***

## Handling default parameters `Default Parameters`

```js
function createStatus(status = "WAITING", source = "APPLICATION") {
    return { status, source };
}

// Overwriting both parameters - e.g. for status from an external system
const successStatus = createStatus("SUCCESS", "EXTERNAL_SERVICE");

// Passing only the first parameter - the default value "APPLICATION" will be used for "source"
const waitingStatus = createStatus("WAITING");

// No parameters - both default values will be used
const defaultStatus = createStatus();
```

Output:

```js
// successStatus
{
    status: "SUCCESS",
    source: "EXTERNAL_SERVICE"
}

// waitingStatus
{
    status: "WAITING",
    source: "APPLICATION"
}

// defaultStatus
{
    status: "WAITING",
    source: "APPLICATION"
}
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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, and the optional `goal` query parameter:

```
GET https://docs.eximee.com/documentation/documentation-en/budowanie-aplikacji/logika-biznesowa/scriptcode/materialy-dodatkowe/sciaga-fragmenty-kodow-js.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
