> 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/budowanie-aplikacji/logika-biznesowa/scriptcode/materialy-dodatkowe/sciaga-fragmenty-kodow-js.md).

# Ściąga - fragmenty kodów JS

Poniższe fragmenty kodu przedstawiają przykładowe sposoby realizacji często używanych operacji w **ScriptCode**. Są to uproszczone schematy, które należy samodzielnie dostosować do konkretnego zastosowania, m.in. nazw parametrów, typu artefaktu, oczekiwanego formatu wyniku oraz wymaganej logiki biznesowej.

## Sprawdzanie duplikatów w tablicy

### Sposób 1

Służy do czyszczenia danych. Przechodzi przez tablicę i zwraca nową, z której wycięto duplikaty.

```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;
}
```

### Sposób 2

Przeznacznony wyłącznie do walidacji. Zwraca tylko wartość logiczną true lub false. Pyta: "Czy na tej liście są jakieś powtórzenia?". Nie zwraca oczyszczonych danych.

```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;
}
```

***

## Usuwanie pustych wartości z tablicy

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

***

## Sprawdzanie duplikatów w obiekcie JSON

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

***

## Sprawdzanie czy tablica zawiera element

### Sposób 1

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

### Sposób 2

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

***

## Wyciąganie danych z timestampa

```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();
```

***

## Pobieranie dzisiejszej daty

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

***

## Wyciąganie nazw plików z komponentu UploadFile

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

***

## Pobieranie wartości konkretnego atrybutu komponentu

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

***

## Usuwanie spacji

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

***

## Dopasowanie wartości do maski (regex)

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

if (!input.match(regex)) {
  Logger.info("Niepoprawny numer dowodu osobistego");
} else {
  return [];
}
```

***

## Zliczanie wystąpień danej wartości

### Sposób 1

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

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

### Sposób 2

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

***

## Sprawdzanie ile pełnych lat minęło

```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("Minęło co najmniej 18 lat");
  } else {
    Logger.info("Nie minęło 18 lat");
  }
} else {
  return [];
}
```

***

## Pobieranie danych z sekcji powtarzalnej

```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++;
}
```

***

## Wywołanie ServiceProxy

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

***

## Utworzenie słownika

### Sposób 1

```js
const items = {
  "Dowód osobisty": "DO",
  "Paszport polski": "PP",
  "Paszport zagraniczny": "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;
```

### Sposób 2

```js
const items = {
  "Dowód osobisty": "DO",
  "Paszport polski": "PP",
  "Paszport zagraniczny": "PZ",
};

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

return dict;
```

***

## Formatowanie liczb zmiennoprzecinkowych

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

***

## Zwracanie dopisku dzień/miesiąc/rok

```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;
}
```

***

## Tworzenie tablicy z listy obiektów

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

***

## Filtrowanie tablicy

```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) }];
}
```

***

## Usuwanie wybranych parametrów obiektu

### Sposób 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) }];
}
```

### Sposób 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) }];
}
```

## Usuwanie duplikatów z tablicy za pomocą `Set`

```js
// Wartości do tablicy
const accountPermissionArr = accountPermissionInput.toArray();

// Set usuwa duplikaty (w JS zachowuje kolejność dodawania elementów)
const accountPermissionSet = new Set(accountPermissionArr);

// Przekształcamy obiekt typu Set z powrotem w tablicę
const accountPermissionFinal = Array.from(accountPermissionSet);

// (opcjonalnie) jeśli chcesz posortować wynik alfabetycznie:
// const accountPermissionFinal = Array.from(accountPermissionSet).sort();
```

***

## Pobieranie wartości za pomocą `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";
}

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

***

## Stworzenie BigDecimala i przydatne dodatki

```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 {
    // domyślnie: usuń białe znaki i zamień przecinek na kropkę
    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);
}
```

***

## Formatowanie salda konta

```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: "," },
  };

  // pozwól na 0, odrzuć 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
  );
}
// Zwraca np.: "79 561,00 PLN" (PL) lub "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()))
    : "";
}
// Zwraca format neutralny (EN) np.: "79561.00"
```

***

## Utworzenie i wyrzucanie błędu biznesowego

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

// Przykład wyrzucenia błędu:
const pesel = context.getFirstParameter("pesel");

if (isInputEmpty(pesel)) {
  throwBusinessError(
    "error_page_default-*",
    "Nie udało się pobrać danych klienta.",
  );
}
```

***

## Wykorzystanie Spread operatora `...`

### Sposób 1

Przykład rozszerzenia danych klienta.

```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"
}
```

### Sposób 2

Przykład połączenia dwóch list w jedną.

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

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

***

## Obsługa parametrów domyślnych `Default Parameters`

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

// Nadpisanie obu parametrów - np. dla statusu z systemu zewnętrznego
const successStatus = createStatus("SUCCESS", "EXTERNAL_SERVICE");

// Przekazanie tylko pierwszego parametru - dla "source" użyta zostanie wartość domyślna "APPLICATION"
const waitingStatus = createStatus("WAITING");

// Brak parametrów - użyte zostaną obie wartości domyślne
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/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.
