# Cheat sheet - JS code snippets

## Checking for duplicates in an array

```js
// Method 1
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
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 listaGrupBezDuplikatow = listaGrup.filter((thing, index, self) =>
  index === self.findIndex(t => JSON.stringify(t) === JSON.stringify(thing))
);
```

***

## Checking whether an array contains an element

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

***

## Extracting data from a timestamp

```js
const dataUrodzenia = context.getFirstParameter("dataUrodzenia");
let data = parseInt(dataUrodzenia);
data = new Date(data);
const rok = data.getFullYear();
const miesiac = data.getMonth() + 1;
const dzien = data.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 nazwy = JSON.parse(context.getFirstParameter("zalaczniki"));
const gotowaLista = nazwy.toString();
```

***

## Getting the value of a specific component attribute

```js
const nazwy = context.getData("@GesUploadFile1", "fileNames");
const rozmiary = 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)) {
  context.log().info("Invalid identity card number");
} else {
  return [];
}
```

***

## Counting occurrences of a given value

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

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

***

## Checking how many full years have passed

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

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

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

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

***

## Getting data from a repeatable section

```js
const pesel = context.getParameters("pesel").toArray();
const data = context.getParameters("dataUrodzenia").toArray();

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

  const ob = context.getData(idObywatelstwo, "label");

  const idImie =
    "GesComplexComponent2.GesComplexComponent3.GesRepeatableSection2.row" +
    index +
    ".GesComplexComponent2.GesComplexComponent3.GesComplexComponent1.GesTextField1";

  const im = context.getData(idImie, "value");

  const isRowVisible = context.isVisible(
    "GesComplexComponent2.GesComplexComponent3.GesRepeatableSection2.row" +
      index +
      ".GesComplexComponent2.GesComplexComponent3.GesComplexComponent1.GesCombobox2"
  );

  if (isRowVisible && im) {
    obywatelstwoList.push(ob);
    stanCywilnyList.push(sc);
    rodzajDokumentuList.push(rd);
  }
  index++;
}
```

***

## ServiceProxy call

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

result = result.get(0).get("result");
parsedResult = JSON.parse(result);
```

***

## Creating a dictionary

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

***

## Formatting floating-point numbers

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

***

## Returning the suffix day/month/year

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

  if (unit === "DAY") {
    literal = quantity === 1 ? "day" : "days";
  }

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

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

  return literal;
}
```

***

## Creating an array from a list of objects

```js
const gotowaListaSchematow = listaSchematowBezDuplikatow.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

```js
// Method 1
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
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);

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

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

***

## Getting a value 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 additions

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


---

# 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.eximee.com/documentation/documentation-en/budowanie-aplikacji/logika-biznesowa/scriptcode/materialy-dodatkowe/sciaga-fragmenty-kodow-js.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.
