---
title: Prototypes
project: Total.js V5
version: 0.0.20
section: reference
language: en
license: MIT
url: https://totaljs.es/docs/total-js-v5/0-0-20/reference/prototypes/
updated: 2026-11-18T16:57:14.575Z
---

# Prototypes

> Every method that Total.js adds to String, Number, Date and Array.prototype.

Methods that Total.js 5 adds to the built-in prototypes `String`, `Number`, `Date` and `Array`. They are available everywhere once the framework is loaded. The guide [Prototypes](../../guides/prototypes/) shows how to use them together with examples; this page is the exact reference.

## API

### str.format(arg0, [arg1], [...])

Type: `method`

Replaces numbered placeholders {0}, {1}, ... with the arguments.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `arg0...argN` | `Any` | yes |  | Values for `{0}`, `{1}` and so on. |

Returns: `String` The new string.

Each `{n}` is replaced with the argument at index `n`. A placeholder whose argument is `null` or `undefined` becomes an empty string. Only numbers are allowed inside the braces; use `String.args()` for named keys.

Example: Numbered placeholders
```js
'Hello {0}, you have {1} messages.'.format('Peter', 5);
// Hello Peter, you have 5 messages.
```

### str.args(obj, [encode], [def])

Type: `method`

Replaces named placeholders {key} or {{key}} with values of an object.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `obj` | `Object` | yes |  | The values. |
| `encode` | `String|Function` | no |  | `html`, `json`, a function `(value, key)` or any other string for URL encoding. |
| `def` | `String` | no |  | The text for keys without a value. |

Returns: `String` The new string.

`String.arg()` is the same method. A placeholder is a key in single or double braces; spaces inside the braces are trimmed. Keys are read directly from `obj` (no nested paths).

`encode` changes the output of each value: `'html'` encodes it with `String.encode()`, `'json'` writes `JSON.stringify(value)`, any other truthy string uses `encodeURIComponent()`, and a function `(value, key)` returns the text itself. When `encode` is a string it also replaces `def`: with `'html'` or a URL-encoding string, a key without a value becomes the text of `encode`; with `'json'` it becomes `undefined`. Without `encode`, a key without a value is left as it is, or replaced with `def` when you pass one.

Example: Named placeholders
```js
var tpl = 'Hello {name}, your order {{ id }} is ready.';
tpl.args({ name: 'Peter', id: 'A100' });
// Hello Peter, your order A100 is ready.

'<b>{name}</b>'.args({ name: '<script>' }, 'html');
// <b>&lt;script&gt;</b>
```

### str.slug([max])

Type: `method`

Makes a URL-friendly slug from the text.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `max` | `Number` | no | `60` | The maximum length of the slug. |

Returns: `String` The slug.

The text is trimmed, lowercased and diacritics are removed (`toASCII()`). Letters, digits and `_` are kept; spaces and the characters `!"#$%&'()*+,-./` become a single `-`; other characters are dropped. A trailing `-` is removed and the result has at most `max` characters.

When the text contains a character without an ASCII form whose code is above 540 (for example Cyrillic letters, `€` or an emoji), the whole text is not slugged letter by letter: the method then returns a short hash-based identifier made from the text, so the result is still stable and URL-safe.

Example: Slug a title
```js
' Hello World! Čaute 123 '.slug();
// hello-world-caute-123

'A very long article title'.slug(10);
// a-very-lon
```

### str.max(length, [chars])

Type: `method`

Shortens the text to a maximum length and adds an ellipsis.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `length` | `Number` | yes |  | The maximum length of the result. |
| `chars` | `String` | no | `'...'` | The text appended to a shortened string. |

Returns: `String` The text, shortened when needed.

When the text is longer than `length`, it is cut so that the result including `chars` has exactly `length` characters. Shorter text is returned unchanged.

Example: Shorten
```js
'Hello world'.max(8);       // Hello...
'Hello world'.max(8, '…');  // Hello w…
```

### str.capitalize([first])

Type: `method`

Capitalizes the first letter of every word, or only of the text.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `first` | `Boolean` | no | `false` | Capitalize only the first character. |

Returns: `String` The new string.

The text is lowercased first. Without arguments every letter after a space, tab or new line becomes uppercase. With `first` set to `true`, only the first character is uppercased and the rest stays lowercase.

Example: Capitalize
```js
'hello WORLD'.capitalize();      // Hello World
'hello WORLD'.capitalize(true);  // Hello world
```

### str.toName()

Type: `method`

Cleans a person name: removes digits and symbols, extra spaces and capitalizes words.

Returns: `String` The cleaned name.

Only ASCII letters, characters above code 127 (letters with diacritics) and spaces are kept. Repeated spaces are reduced to one, trailing spaces are removed (leading spaces become one space) and the first letter of each word is uppercased. The rest of each word is kept as it is.

Example: Clean a name
```js
'peter   sirka 12'.toName();
// Peter Sirka
```

### str.encode()

Type: `method`

Encodes HTML special characters.

Returns: `String` The encoded text.

`String.safehtml()` is the same method. The characters `<`, `>`, `"`, `'` and `&` are replaced with `&lt;`, `&gt;`, `&quot;`, `&apos;` and `&amp;`. Use it before you put user text into HTML.

Example: Encode user input
```js
'<a href="x">Tom & Jerry</a>'.encode();
// &lt;a href=&quot;x&quot;&gt;Tom &amp; Jerry&lt;/a&gt;
```

### str.decode()

Type: `method`

Decodes HTML entities back to characters.

Returns: `String` The decoded text.

Named entities (`&lt;`, `&amp;`, `&quot;`, ...) and numeric entities (`&#65;`, `&#x41;`) are replaced with their characters. Unknown named entities stay as they are.

Example: Decode
```js
'&lt;b&gt;Tom &amp; Jerry&#33;&lt;/b&gt;'.decode();
// <b>Tom & Jerry!</b>
```

### str.removeTags()

Type: `method`

Removes HTML tags from the text.

Returns: `String` The text without tags.

Every `<...>` tag (opening or closing) is removed; the text between tags stays. The result is not HTML-encoded, so encode it with `String.encode()` when you write it back into HTML.

Example: Strip tags
```js
'<p><b>Hi</b> there</p>'.removeTags();
// Hi there
```

### str.padLeft(max, [c])

Type: `method`

Pads the text on the left to a length. String.padRight() pads on the right.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `max` | `Number` | yes |  | The length of the result. |
| `c` | `String` | no | `' '` | The padding character. |

Returns: `String` The padded text.

Characters `c` are added until the text has `max` characters; longer text is returned unchanged. `str.padRight(max, [c])` works the same way on the right side. Both are defined only when the runtime does not already have them.

Example: Pad
```js
'5'.padLeft(3, '0');   // 005
'a'.padRight(3, '-');  // a--
```

### str.toASCII()

Type: `method`

Replaces letters with diacritics by their ASCII form.

Returns: `String` The text without diacritics.

Letters such as `č`, `á` or `ü` are replaced with `c`, `a` and `u`. Characters without an ASCII form stay as they are.

Example: Remove diacritics
```js
'Čučoriedka'.toASCII();
// Cucoriedka
```

### str.toKeywords([forsearch], [alternative], [max_count], [max_length], [min_length])

Type: `method`

Extracts keywords from the text, the most frequent first.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `forsearch` | `Boolean` | no | `true` | Normalize the words for search. |
| `alternative` | `Boolean` | no | `false` | Shorten words to 80 % of their length. |
| `max_count` | `Number` | no | `200` | The maximum number of words to read. |
| `max_length` | `Number` | no | `20` | The maximum length of a keyword. |
| `min_length` | `Number` | no | `2` | The minimum length of a keyword. |

Returns: `Array` Unique keywords sorted by frequency.

The text is lowercased and split into words; characters that are not letters or digits are removed from each word. With `forsearch` (default) diacritics are removed and `y` becomes `i`, which makes matching tolerant. `alternative` keeps only the first 80 % of longer words (a simple stem). Words shorter than `min_length` or longer than `max_length` are skipped and at most `max_count` words are read. The unique words are returned sorted by how often they appear.

For a single normalized search string use `str.toSearch()`: it lowercases the text, removes diacritics and symbols, replaces `y` with `i` and drops repeated letters (`hello` becomes `helo`).

Example: Keywords for a search index
```js
'Total.js is a great framework, great!'.toKeywords();
// ['great', 'totaljs', 'is', 'framework']

'Čaute Hello'.toSearch();
// caute helo
```

### str.pluralize(zero, one, few, other)

Type: `method`

Converts the text to a number and picks a plural form.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `zero` | `String` | yes |  | Text for 0, or all four forms separated by commas. |
| `one` | `String` | no |  | Text for 1. |
| `few` | `String` | no |  | Text for 2 to 4. |
| `other` | `String` | no |  | Text for other numbers. |

Returns: `String` The chosen form.

The text is converted with `parseInt()` and the result is passed to `Number.pluralize()`.

Example: Pluralize a string
```js
'3'.pluralize('no items', '# item', '# items', '# items');
// 3 items
```

### str.parseInt([def])

Type: `method`

Converts the text to a number, with a default for invalid text.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `def` | `Number` | no | `0` | The value for text that is not a number. |

Returns: `Number` The number or the default.

The text is trimmed and converted with the unary `+`, so `'10'` is `10`, `'1.5'` is `1.5` and `'0x10'` is `16`. When the text is not a number, `def` is returned (`0` when you omit it).

`str.parseInt2([def])` finds the first integer anywhere in the text instead (`'abc 123'` gives `123`); `str.parseFloat2([def])` does the same for a decimal number and accepts `,` as the decimal separator.

Example: Read numbers
```js
'10'.parseInt();        // 10
'abc'.parseInt(5);      // 5
'Total: 123 EUR'.parseInt2(); // 123
'x 1,5 y'.parseFloat2();      // 1.5
```

### str.parseFloat([def])

Type: `method`

Converts the text to a decimal number; a comma is accepted as the decimal separator.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `def` | `Number` | no | `0` | The value for text that is not a number. |

Returns: `Number` The number or the default.

The text is trimmed, the first `,` is replaced with `.` and the text is converted to a number. When the text is not a number, `def` is returned (`0` when you omit it).

Example: Read decimals
```js
'1,5'.parseFloat();    // 1.5
' 2.25 '.parseFloat(); // 2.25
'n/a'.parseFloat(-1);  // -1
```

### str.parseBoolean()

Type: `method`

Converts the text to a boolean.

Returns: `Boolean`

Returns `true` for `true`, `1` and `on` (case-insensitive) and `false` for everything else.

Example: Read a flag
```js
'on'.parseBoolean();    // true
'TRUE'.parseBoolean();  // true
'no'.parseBoolean();    // false
```

### str.parseDate([format])

Type: `method`

Converts the text to a Date.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `format` | `String` | no |  | A format such as `dd/MM/yyyy HH:mm`. |

Returns: `Date` The parsed date.

Without `format` the method understands:

- JSON dates (`2024-05-01T12:30:00.000Z`),
- `yyyy-MM-dd`, `yyyy-MM-dd HH:mm`, `yyyy-MM-dd HH:mm:ss` and `yyyy-MM-ddTHH:mm:ss.SSS`,
- `d.M.yyyy` with an optional time (`1.5.2024 08:00`),
- anything else that `new Date(text)` accepts.

The date and time of these forms are read as UTC. Missing parts of the date are taken from today.

With `format` the digits of the text are read by the positions of `yyyy`, `MM`, `dd`, `HH`, `mm` and `ss` in the format; the other characters of the format only separate the parts. The parts must be written with all their digits (`05`, not `5`). A two-digit year is in the 2000s, and `pm` in the text adds 12 hours.

Example: Parse dates
```js
'2024-05-01 12:30'.parseDate();
// 2024-05-01T12:30:00.000Z

'1.5.2024'.parseDate();
// 2024-05-01T00:00:00.000Z

'01/05/2024'.parseDate('dd/MM/yyyy');
// 1 May 2024
```

### str.parseDateExpiration()

Type: `method`

Converts a relative time such as "5 minutes" to a Date in the future.

Returns: `Date` The current time plus the given duration.

The text is a list of pairs `number unit` separated by spaces. Each pair is added to the current time with `Date.add()`, so all units of `Date.add()` work (`seconds`, `minutes`, `hours`, `days`, `weeks`, `months`, `years` and their short forms). Use a negative number for a date in the past.

Example: Expiration
```js
var expire = '5 minutes'.parseDateExpiration();
var later = '1 day 2 hours'.parseDateExpiration();
```

### str.parseJSON([date])

Type: `method`

Parses JSON without throwing.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `date` | `Boolean` | no | `false` | Convert JSON date strings to Date objects. |

Returns: `Object` The parsed value or `undefined`.

Returns the parsed value, or `undefined` when the text is not valid JSON. With `date` set to `true`, strings in the JSON date format (`2024-01-01T10:00:00.000Z`) become `Date` objects.

Example: Safe parse
```js
var obj = '{"a":1}'.parseJSON();          // { a: 1 }
var bad = '{a:1'.parseJSON();             // undefined
var doc = '{"created":"2024-01-01T10:00:00.000Z"}'.parseJSON(true);
doc.created instanceof Date;             // true
```

### str.parseCSV([delimiter])

Type: `method`

Parses CSV text into an array of objects with column keys a, b, c, ...

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `delimiter` | `String` | no | `','` | The column delimiter, one character. |

Returns: `Array` An array of objects.

Each line becomes an object. The keys are column letters: `a` for the first column, `b` for the second, ..., `z`, then `aa`, `ab` and so on. Values in double quotes may contain the delimiter and new lines; `""` inside quotes is an escaped quote. Empty columns have no key in the object. Values are strings and are not trimmed. A header line is returned like any other line.

Example: Parse CSV
```js
var rows = 'name,age\n"Sirka, Peter",40\nAnna,'.parseCSV();
// [{ a: 'name', b: 'age' }, { a: 'Sirka, Peter', b: '40' }, { a: 'Anna' }]

var header = rows.shift();
for (var row of rows)
	console.log(row.a, row.b || '-');
```

### str.parseContext()

Type: `method` · Since: `0.0.17`

Parses a text made of blocks with a header and a body.

Returns: `Array` An array of objects, one per block.

Each block starts with a line of at least 20 dashes, followed by header lines `key: value`, another line of at least 20 dashes and the body. The body ends where the next block starts. Every block becomes an object with the header keys (lowercased, values trimmed) and a `body` property with the trimmed body. Header lines without `:` are ignored.

Example: Parse blocks
```js
var text = [
	'--------------------',
	'Name: Hello',
	'Type: note',
	'--------------------',
	'Body one',
	'--------------------',
	'Name: Second',
	'--------------------',
	'Body two'
].join('\n');

text.parseContext();
// [{ name: 'Hello', type: 'note', body: 'Body one' }, { name: 'Second', body: 'Body two' }]
```

### str.parseEncoded()

Type: `method`

Parses URL-encoded text (a query string or a form body) into an object.

Returns: `Object` The parsed keys and values (strings).

Pairs `key=value` are separated by `&`; keys and values are URL-decoded. This is the parser that Total.js uses for query strings and `application/x-www-form-urlencoded` bodies.

Example: Parse a query string
```js
'q=total.js&page=2&name=%20Peter'.parseEncoded();
// { q: 'total.js', page: '2', name: ' Peter' }
```

### str.parseConfig([def], [onerr])

Type: `method`

Parses text in the Total.js configuration format into an object.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `def` | `Object` | no |  | Default values copied into the result first. |
| `onerr` | `Function` | no |  | `function(err, line)` for values that cannot be evaluated. |

Returns: `Object` The parsed values.

Each line is `key : value`. The separator is the first `:`, or the first `=` when the line has no `:`; the value starts at the second character after the separator, so keep one space there. Empty lines and lines that start with `#` or `//` are skipped. A value that starts with `base64 ` or `hex ` is decoded.

A type in brackets after the key converts the value: `(string)`, `(number)` (also `float`, `double`, `currency`), `(boolean)` / `(bool)` (true when the value contains `true`, `on`, `1` or `enabled`, in any case), `(json)`, `(object)` / `(array)` / `(eval)` (evaluated as JavaScript), `(date)`, `(env)` (reads `process.env[value]`), `(config)` (reads another configuration key) and `(random)` (a random string of the given length). When an evaluated value fails, `onerr(err, line)` is called, or an error is thrown without it.

Example: Parse settings
```js
var text = 'name : Shop\ncount (number) : 10\nenabled (boolean) : true\n# comment\ntags (array) : [\'a\', \'b\']';
text.parseConfig();
// { name: 'Shop', count: 10, enabled: true, tags: ['a', 'b'] }
```

### str.parseEnv()

Type: `method`

Parses text in the .env format into an object.

Returns: `Object` The keys and values.

Each line is `KEY=value`. Lines that are empty or start with `#` or `//` are skipped. A value in single or double quotes is unquoted (its inner spaces are kept); other values are trimmed. `\n` in a value becomes a new line. All values are strings.

Example: Parse .env
```js
'PORT=8000\nNAME="My app"\n# comment'.parseEnv();
// { PORT: '8000', NAME: 'My app' }
```

### str.parseUA([structured])

Type: `method`

Reads the operating system, browser and device type from a User-Agent header.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `structured` | `Boolean` | no | `false` | Return an object instead of text. |

Returns: `String|Object`

Without arguments the result is a short text such as `Windows Chrome`. With `structured` set to `true` the result is an object `{ os, browser, device }`, where `device` is `mobile` or `desktop`. Empty text returns an empty string.

Example: Read the user agent
```js
var ua = 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) Version/17.0 Mobile Safari/604.1';
ua.parseUA();      // iPhone Safari
ua.parseUA(true);  // { os: 'iPhone', browser: 'Safari', device: 'mobile' }
```

### str.isEmail()

Type: `method`

Checks that the text is an e-mail address.

Returns: `Boolean`

The test uses the `email` regular expression of `DEF.validators`: letters, digits and `-_.+` before `@`, a domain and a top-level domain of at least two letters. Text of four characters or less is never valid.

Example: Validate
```js
'info@example.com'.isEmail();  // true
'info@example'.isEmail();      // false
```

### str.isPhone()

Type: `method`

Checks that the text is a phone number.

Returns: `Boolean`

The test uses the `phone` regular expression of `DEF.validators`: an optional `+`, three digits (optionally in brackets), three digits and 4 to 8 digits, each group optionally separated by `-`, `.` or a space. Text shorter than six characters is never valid.

Example: Validate
```js
'+421903123456'.isPhone();  // true
'(123) 456-7890'.isPhone(); // true
'12345'.isPhone();          // false
```

### str.isURL()

Type: `method`

Checks that the text is an http or https URL.

Returns: `Boolean`

The text must start with `http://` or `https://` and must not contain `,`, `{`, `}` or `\`. Text of seven characters or less is never valid.

Example: Validate
```js
'https://www.totaljs.com'.isURL();  // true
'www.totaljs.com'.isURL();          // false
```

### str.isUID()

Type: `method`

Checks that the text is a valid identifier made by UID().

Returns: `Boolean`

The method checks the format and the checksum of identifiers created by `UID()`, so a random string of the same shape is rejected. To read the date and index stored in a UID use `str.parseUID()`, which returns `{ version, date, century, hash, index, valid }`. For standard GUIDs (`8-4-4-4-12` hex digits) use `str.isGUID()`.

Example: Validate an id
```js
var id = UID();
id.isUID();       // true
'abc'.isUID();    // false
id.parseUID().date;  // the time the id was created
'123e4567-e89b-12d3-a456-426614174000'.isGUID(); // true
```

### str.isNumber([isDecimal])

Type: `method`

Checks that the text contains only digits.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `isDecimal` | `Boolean` | no | `false` | Allow one decimal separator. |

Returns: `Boolean`

Every character must be a digit. With `isDecimal` set to `true`, one `.` or `,` is allowed as well. A sign (`-`, `+`) is not allowed and empty text is not a number.

Example: Validate
```js
'0123'.isNumber();      // true
'1.5'.isNumber();       // false
'1,5'.isNumber(true);   // true
```

### str.isJSON()

Type: `method`

Quickly checks that the text looks like a JSON object, array or string.

Returns: `Boolean`

Leading and trailing white space is skipped and the first and last characters are compared: `{` with `}`, `[` with `]` or `"` with `"`. It is also `true` when the text starts with a digit or a letter and ends with a character below `9`, for example `'123'` or `'abc1'`. The content is not parsed, so use `String.parseJSON()` when you need to be sure.

Example: Check before parsing
```js
var body = ' {"a":1} ';
if (body.isJSON())
	var obj = body.parseJSON();
```

### str.isXSS()

Type: `method`

Checks that the text contains an HTML tag.

Returns: `Boolean`

Returns `true` when the text contains `<` followed later by `>`, which is how the `xss` regular expression of `DEF.validators` detects markup in user input. `str.isSQLInjection()` works the same way with the `sqlinjection` expression: it is `true` for quoted strings and for the SQL keywords `ALTER`, `CREATE`, `DELETE`, `DROP`, `EXEC`, `INSERT`, `MERGE`, `SELECT`, `UPDATE` and `UNION` written in uppercase. Both are simple filters, not a replacement for encoding output and for query parameters.

Example: Reject markup
```js
'<script>alert(1)</script>'.isXSS();  // true
'Hello'.isXSS();                      // false
'DROP TABLE users'.isSQLInjection();   // true
```

### str.hash([type], [salt])

Type: `method`

Returns a hash of the text: a fast number hash or an md5, sha1, sha256, sha512 or crc32 digest.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `type` | `String|Boolean` | no |  | `md5`, `sha1`, `sha256`, `sha512`, `crc32`, `crc32unsigned`, or `true` for an unsigned number hash. |
| `salt` | `String` | no |  | Text appended before hashing. |

Returns: `Number|String` A number for the number hash and crc32, a hex string otherwise.

`type` selects the algorithm: `md5`, `sha1`, `sha256`, `sha512` (hex strings), `crc32` (signed number) or `crc32unsigned` (unsigned number). Without `type` the method returns a fast 32-bit number hash of the text (signed); `hash(true)` returns it unsigned. `salt` is appended to the text before hashing. The number hash is not a cryptographic hash: use it for cache keys and similar purposes. `str.crc32([unsigned])` is also available directly.

Example: Hashes
```js
'hello'.hash();          // a signed 32-bit number
'hello'.hash(true);      // the same, unsigned
'hello'.hash('sha256');  // hex digest
'hello'.hash('crc32unsigned');
```

### str.md5([salt])

Type: `method`

Returns the MD5 digest of the text as a hex string.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `salt` | `String` | no |  | Text appended before hashing. |

Returns: `String` 32 hex characters.

The text (with `salt` appended) is hashed as UTF-8 with Node.js `crypto`. MD5 is suitable for checksums and cache keys, not for passwords.

Example: MD5
```js
'a'.md5();
// 0cc175b9c0f1b6a831c399e269772661
```

### str.sha256([salt])

Type: `method`

Returns the SHA-256 digest of the text as a hex string. sha1() and sha512() work the same.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `salt` | `String` | no |  | Text appended before hashing. |

Returns: `String` 64 hex characters.

The text (with `salt` appended) is hashed as UTF-8 with Node.js `crypto`. `str.sha1([salt])` returns 40 hex characters and `str.sha512([salt])` 128 hex characters.

Example: SHA digests
```js
var digest = 'password'.sha256(CONF.secret);
var short = 'text'.sha1();
var long = 'text'.sha512();
```

### str.sign([key], [check])

Type: `method`

Signs the text with a short checksum, or checks and removes the signature.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `key` | `String` | no |  | The signing key. |
| `check` | `Boolean` | no | `false` | Check the signature and return the original text. |

Returns: `String` The signed text, the original text, or `null`.

`str.sign(key)` returns `text-checksum`, where the checksum is made from the text and `key`. `signed.sign(key, true)` checks the checksum and returns the original text, or `null` when the signature does not match. Use it for values that travel through URLs and must not be changed, such as ids in links. It is not encryption: the text stays readable.

`str.makeid()` returns only a short base-36 checksum of the text, handy as a compact key.

Example: Sign an id
```js
var token = '123'.sign('mykey');     // 123-155hlxd
token.sign('mykey', true);           // 123
(token + 'x').sign('mykey', true);   // null
```

### str.encrypt(key, [isUnique], [secret])

Type: `method`

Encrypts the text with a key. String.decrypt() reverses it.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `key` | `String` | yes |  | The encryption key. |
| `isUnique` | `Boolean` | no | `false` | Make a different result for each call. |
| `secret` | `String` | no | `CONF.secret` | The secret used in the checksum. |

Returns: `String` The encrypted text.

The result is a string of a checksum, `-` and hex data. With `isUnique` set to `true`, the same text gives a different result each time. The checksum uses `secret`, or the `secret` configuration key when you omit it.

`str.decrypt(key, [secret])` returns the original text, or `null` when the key, the secret or the data do not match. Use the same `key` and `secret` for both.

Example: Encrypt and decrypt
```js
var value = 'user@example.com'.encrypt('mykey', true);
value.decrypt('mykey');   // user@example.com
value.decrypt('other');   // null
```

### str.encrypt_uid([key])

Type: `method`

Encrypts an identifier into a short URL-safe token. String.decrypt_uid() reverses it.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `key` | `String` | no | `CONF.secret` | The key. |

Returns: `String` The token.

Use it to hide numeric or text ids in public URLs. `key` defaults to the `secret` configuration key. `token.decrypt_uid([key])` returns the original id, or `null` when the token was changed or the key is different.

Example: Hide an id
```js
var token = '123'.encrypt_uid('mykey');
token.decrypt_uid('mykey');  // 123
```

### str.base64ToBuffer()

Type: `method`

Converts base64 text or a data URI to a Buffer.

Returns: `Buffer` The decoded data.

Everything up to and including the first `,` is skipped, so both plain base64 and `data:...;base64,...` work. Related methods: `str.base64ToFile(filename, [callback])` writes the decoded data to a file, `str.base64ContentType()` returns the content type of a data URI (`image/png`), and `str.parseDataURI()` returns `{ type, buffer }` (or `null` for text that is not a data URI).

Example: Decode an upload
```js
var uri = 'data:text/plain;base64,aGVsbG8=';
uri.base64ToBuffer().toString();   // hello
uri.base64ContentType();           // text/plain
uri.parseDataURI().type;           // text/plain
uri.base64ToFile(PATH.temp('hello.txt'));
```

### num.format([decimals], [separator], [separatorDecimal])

Type: `method`

Formats a number with a thousands separator and a fixed number of decimals.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `decimals` | `Number` | no |  | The number of decimals. |
| `separator` | `String` | no | `' '` | The thousands separator. |
| `separatorDecimal` | `String` | no | `'.'` | The decimal separator. |

Returns: `String` The formatted number.

The thousands separator is a space by default. The decimal separator is `.`, or `,` when the thousands separator is `.`. Extra decimals are cut, not rounded, so call `Number.round()` first when you need rounding. Missing decimals are filled with zeros. When the first argument is a string, the first two arguments are swapped: `format('.', 2)` is the same as `format(2, '.')`.

Example: Format
```js
(1234567.891).format(2);           // 1 234 567.89
(1234.5).format(2, ',', '.');      // 1,234.50
(1234.5).format('.', 2);           // 1.234,50
(1.999).round(2).format(2);        // 2.00
```

### num.pluralize(zero, one, few, other)

Type: `method`

Picks a plural form by the number; # is replaced with the number.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `zero` | `String` | yes |  | Text for 0, or all four forms separated by commas. |
| `one` | `String` | no |  | Text for 1. |
| `few` | `String` | no |  | Text for 2 to 4. |
| `other` | `String` | no |  | Text for other numbers. |

Returns: `String` The chosen form.

The form `zero` is used for 0, `one` for 1, `few` for 2 to 4 and `other` for the rest (the rule of Slavic languages; for English pass the same text as `few` and `other`). When you pass only one string, it is split by commas into the four forms. The first `#` in the chosen form is replaced with the number.

Example: Plural forms
```js
(1).pluralize('no items', '# item', '# items', '# items');  // 1 item
(7).pluralize('no items,# item,# items,# items');          // 7 items
```

### num.padLeft(max, [c])

Type: `method`

Pads the number on the left with zeros. Number.padRight() pads on the right.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `max` | `Number` | yes |  | The length of the result. |
| `c` | `String` | no | `'0'` | The padding character. |

Returns: `String` The padded number.

The number is converted to a string and padded to `max` characters with `c` (`0` by default). `num.padRight(max, [c])` pads on the right.

Example: Zero padding
```js
(5).padLeft(3);       // 005
(7).padLeft(4, ' ');  // '   7'
(5).padRight(3);      // 500
```

### num.round(precision)

Type: `method`

Rounds the number to a number of decimals.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `precision` | `Number` | yes |  | The number of decimals. |

Returns: `Number` The rounded number.

Rounding uses exponent notation, so values like `1.005` round correctly to `1.01`. `num.floor(decimals)` rounds down to a number of decimals instead (`(1.239).floor(2)` is `1.23`).

Example: Round
```js
(1.005).round(2);  // 1.01
(2.5).round(0);    // 3
(1.239).floor(2);  // 1.23
```

### num.fixed(decimals)

Type: `method`

Rounds the number with toFixed() and returns a number, not a string.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `decimals` | `Number` | yes |  | The number of decimals. |

Returns: `Number`

Example: Fixed
```js
(1.236).fixed(2);  // 1.24 (a number)
```

### num.between(condition, [otherwise])

Type: `method`

Returns the value of the first range that contains the number.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `condition` | `Object` | yes |  | Ranges as keys, results as values. |
| `otherwise` | `Any` | no |  | The result when no range matches. |

Returns: `Any` The value of the matching range or `otherwise`.

`condition` is an object whose keys are ranges: `'1-3'` (from 1 to 3, both included), `'7-'` (7 and more) or `'-5'` (5 and less). The keys are tested in order and the value of the first matching key is returned. When no range matches, `otherwise` is returned.

Example: Grade a score
```js
var score = 5;
score.between({ '0-3': 'low', '4-6': 'medium', '7-': 'high' }, 'unknown');
// medium
```

### num.VAT(percentage, [decimals], [includedVAT])

Type: `method`

Adds a tax to the number, or removes it from a price that includes it.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `percentage` | `Number` | yes |  | The tax rate in percent. |
| `decimals` | `Number` | no | `2` | The number of decimals. |
| `includedVAT` | `Boolean` | no | `false` | The number already includes the tax. |

Returns: `Number`

`Number.TAX()` is the same method. Without `includedVAT` the result is the number increased by `percentage`. With `includedVAT` set to `true` the number is a price that already includes the tax, and the result is the price without the tax. The result is rounded to `decimals` (2 by default). You can pass the boolean as the second argument: `VAT(20, true)`.

Example: Prices with VAT
```js
(100).VAT(20);        // 120
(120).VAT(20, true);  // 100
(99.99).TAX(10, 0);   // 110
```

### num.discount(percentage, [decimals])

Type: `method`

Reduces the number by a percentage.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `percentage` | `Number` | yes |  | The discount in percent. |
| `decimals` | `Number` | no | `2` | The number of decimals. |

Returns: `Number`

The result is rounded down to `decimals` (2 by default).

Example: Discount
```js
(100).discount(15);    // 85
(19.99).discount(10);  // 17.99
```

### num.filesize([decimals], [type])

Type: `method`

Formats a number of bytes as a human-readable size.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `decimals` | `Number` | no |  | The number of decimals. |
| `type` | `String` | no |  | `bytes`, `KB`, `MB`, `GB` or `TB`. |

Returns: `String` The size with its unit.

Without `type` the largest fitting unit is chosen: `bytes`, `KB`, `MB`, `GB` or `TB` (1 KB is 1024 bytes). With `type` the value is converted to that unit. Without `decimals` the value has up to two decimals and `.00` is removed; with `decimals` it is formatted with `Number.format(decimals)`. The arguments can be passed in either order.

Example: File sizes
```js
(500).filesize();          // 500 bytes
(1536000).filesize();      // 1.46 MB
(5000000).filesize(1, 'MB'); // 4.7 MB
```

### num.currency([currency], [a], [b], [c])

Type: `method`

Formats the number as an amount with a currency formatter registered in DEF.currencies.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `currency` | `String` | no | `'default'` | The key in `DEF.currencies`. |
| `a, b, c` | `Any` | no |  | Extra arguments for the formatter. |

Returns: `String` The formatted amount.

The formatter is the function `DEF.currencies[currency]` (or `DEF.currencies.default` without `currency`). It receives the number and the arguments `a`, `b` and `c` and returns the text. When no formatter exists for the currency, the result is `num.format(2)`. Register formatters at startup, for example in a definition file.

Example: Register and use a currency
```js
// /definitions/currencies.js
DEF.currencies.eur = function(val) {
	return val.format(2, ' ', ',') + ' €';
};

(1234.5).currency('eur');  // 1 234,50 €
(10).currency('usd');      // 10.00 (no formatter)
```

### date.add(type, [value])

Type: `method`

Returns a new date shifted by an amount of time.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `type` | `String|Number` | yes |  | The unit, a string with value and unit, or milliseconds. |
| `value` | `Number` | no |  | The amount, negative for the past. |

Returns: `Date` A new date.

The original date is not changed. Pass the unit and the value (`add('minutes', 30)`), one string with both (`add('30 minutes')`, `add('-2 hours')`) or a number of milliseconds (`add(5000)`).

Units: `s`, `ss`, `sec`, `second`, `seconds`; `m`, `mm`, `min`, `minute`, `minutes`; `h`, `hh`, `hour`, `hours`; `d`, `dd`, `day`, `days`; `w`, `ww`, `week`, `weeks`; `M`, `MM`, `month`, `months`; `y`, `yyyy`, `year`, `years`. The units work on the UTC parts of the date. Adding months to the end of a month follows JavaScript: 31 January plus one month is 2 March in a leap year and 3 March otherwise.

Example: Shift dates
```js
var now = new Date();
now.add('1 day');
now.add('minutes', 30);
now.add('-2 hours');
now.add(5000);  // + 5 seconds
```

### date.diff([date], type)

Type: `method`

Returns the difference between two dates in seconds, minutes, hours or days.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `date` | `Date|String|Number` | no | `now` | The date to compare with. |
| `type` | `String` | yes |  | The unit of the result. |

Returns: `Number` The difference in the unit.

The result is `this - date` in the given unit, rounded up, so it is positive when `this` is later. `date` can be a Date, a string that `Date.parse()` understands or a number of milliseconds. With one argument the date is compared with the current time. Units: `s` / `ss` / `second` / `seconds`, `m` / `mm` / `minute` / `minutes`, `h` / `hh` / `hour` / `hours`, `d` / `dd` / `day` / `days`. An unknown unit returns `NaN`.

Example: Differences
```js
var created = new Date('2024-01-30T00:00:00Z');
var end = new Date('2024-01-31T10:00:00Z');
end.diff(created, 'hours');  // 34
end.diff('2024-01-01T00:00:00Z', 'days'); // 31
created.diff('seconds');     // negative: created is in the past
```

### date.format([format], [resource])

Type: `method`

Formats the date by a pattern; without a pattern returns an ISO string in UTC.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `format` | `String` | no |  | The pattern. |
| `resource` | `String` | no |  | The resource used for month and day names. |

Returns: `String` The formatted date.

Without `format` the result is `yyyy-MM-ddTHH:mm:ss.SSSZ` in UTC. With `format` the parts are written in the server time zone (UTC unless the `$timezone` configuration key says otherwise):

- `yyyy`, `yy` year; `MM`, `M` month number; `MMMM` month name, `MMM` its first three letters,
- `dd`, `d` day; `dddd` day name, `ddd` its first two letters in uppercase,
- `HH`, `H` hours (0-23); `mm`, `m` minutes; `ss`, `s` seconds,
- `ww`, `w` ISO week number; `a` `AM` or `PM`.

Uppercase `YYYY`, `YY`, `DD`, `D`, `DDDD`, `DDD` and lowercase `hh`, `h` are accepted too. Month and day names are English; with `resource` they are translated with the resource file of that name. Compiled formats are cached, so formatting is fast.

Example: Format dates
```js
var d = new Date('2024-01-31T10:00:00Z');
d.format();                      // 2024-01-31T10:00:00.000Z
d.format('yyyy-MM-dd HH:mm');    // 2024-01-31 10:00
d.format('dd.MM.yy');            // 31.01.24
d.format('dddd, d. MMMM yyyy');  // Wednesday, 31. January 2024
d.format('MMMM', 'sk');          // the month name from sk.resource
```

### date.extend(text)

Type: `method`

Returns a new date with the date or time parts replaced from a text.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `text` | `String` | yes |  | A date, a time, or both. |

Returns: `Date` A new date.

The text can contain a date `yyyy-MM-dd` or `d.M.yyyy` and a time `HH:mm` or `HH:mm:ss`. Only the parts found in the text are replaced; the others are taken from the original date. The year, month and day are set one after another, so when the day of the original date does not exist in the new month the date moves to the next month (31 January extended with `2025-02-10` gives 10 March 2025). The values are UTC.

Example: Change parts
```js
var d = new Date('2024-01-31T10:00:00Z');
d.extend('12:30');              // 2024-01-31T12:30:00.000Z
d.extend('2025-03-04');         // 2025-03-04T10:00:00.000Z
d.extend('1.3.2020 08:00');     // 2020-03-01T08:00:00.000Z
```

### date.toUTC([ticks])

Type: `method`

Shifts a local date by the time zone offset to UTC.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `ticks` | `Boolean` | no | `false` | Return milliseconds. |

Returns: `Date|Number`

The result is the date plus the offset of the server time zone. With `ticks` set to `true` the result is the number of milliseconds instead of a Date. On a server running in UTC (the default) the date does not change.

Example: To UTC
```js
var utc = new Date().toUTC();
var ms = new Date().toUTC(true);
```

### date.setTimeZone(timezone)

Type: `method`

Returns a new date that shows the same moment in another time zone.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `timezone` | `String` | yes |  | An IANA time zone name. |

Returns: `Date` A new date.

The parts of the result (hours, day, ...) read in the server time zone are the wall-clock time of `timezone` at that moment, so `format()` prints the local time of that zone. `timezone` is an IANA name such as `Europe/Bratislava` or `America/New_York`.

Example: Show local time
```js
var d = new Date('2024-01-31T10:00:00Z');
d.setTimeZone('Europe/Bratislava').format('HH:mm');  // 11:00
```

### arr.findItem(cb, [value])

Type: `method`

Returns the first item that matches, or null.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `cb` | `Function|String|Any` | yes |  | A test function, a property name or a value. |
| `value` | `Any` | no |  | The value of the property. |

Returns: `Object` The item or `null`.

Pass a function `(item, index)`, a property name and a value (`('id', 5)` compares `item.id === 5`), or a single value that is compared with `===`.

Example: Find an item
```js
var users = [{ id: 1, name: 'Peter' }, { id: 2, name: 'Anna' }];
users.findItem('id', 2);                  // { id: 2, name: 'Anna' }
users.findItem(u => u.name === 'Peter');  // { id: 1, name: 'Peter' }
users.findItem('id', 9);                  // null
```

### arr.findAll(cb, [value])

Type: `method`

Returns all items that match.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `cb` | `Function|String|Any` | yes |  | A test function, a property name or a value. |
| `value` | `Any` | no |  | The value of the property. |

Returns: `Array` The matching items.

Pass a function `(item, index)`, a property name and a value (`('id', 5)` compares `item.id === 5`), or a single value that is compared with `===`. The result is a new array; the original array is not changed.

Example: Filter
```js
var items = [{ type: 'a' }, { type: 'b' }, { type: 'a' }];
items.findAll('type', 'a').length;  // 2
```

### arr.findIndex(cb, [value])

Type: `method`

Returns the index of the first item that matches, or -1.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `cb` | `Function|String|Any` | yes |  | A test function, a property name or a value. |
| `value` | `Any` | no |  | The value of the property. |

Returns: `Number` The index or `-1`.

Pass a function `(item, index)`, a property name and a value (`('id', 5)` compares `item.id === 5`), or a single value that is compared with `===`. Total.js replaces the native `findIndex()` with this version (with a function it behaves like the native one); `arr.TfindIndex()` is the same method.

Example: Index of an item
```js
var users = [{ id: 1 }, { id: 2 }];
var index = users.findIndex('id', 2);  // 1
if (index !== -1)
	users.splice(index, 1);
```

### arr.findValue(cb, value, path, [def])

Type: `method`

Finds an item and returns one of its properties.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `cb` | `Function|String` | yes |  | A test function or a property name. |
| `value` | `Any` | yes |  | The value of the property (pass `undefined` with a function). |
| `path` | `String` | yes |  | The property to return. |
| `def` | `Any` | no |  | The default value. |

Returns: `Any`

The item is found like in `Array.findItem()`. The result is `item[path]`, or `def` when no item matches or the property is `null` / `undefined`.

Example: Read a property
```js
var users = [{ id: 1, name: 'Peter' }];
users.findValue('id', 1, 'name');          // Peter
users.findValue('id', 9, 'name', 'guest');  // guest
```

### arr.remove(cb, [value])

Type: `method`

Returns a new array without the items that match.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `cb` | `Function|String|Any` | yes |  | A test function, a property name or a value. |
| `value` | `Any` | no |  | The value of the property. |

Returns: `Array` A new array without the matching items.

Pass a function `(item, index)`, a property name and a value (`('id', 5)` compares `item.id === 5`), or a single value that is compared with `===`. The original array is not changed, so assign the result.

Example: Remove items
```js
var users = [{ id: 1 }, { id: 2 }, { id: 3 }];
users = users.remove('id', 1);       // [{ id: 2 }, { id: 3 }]
var nums = [1, 2, 3, 2].remove(2);   // [1, 3]
```

### arr.quicksort([sort], [desc])

Type: `method`

Sorts the array in place by one or more properties.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `sort` | `String|Boolean` | no |  | Properties to sort by, or `true` for descending plain values. |
| `desc` | `Boolean` | no | `false` | Descending order for `sort`. |

Returns: `Array` The same array, sorted.

`sort` is a comma-separated list of property names, each optionally with `_asc` or `_desc` (`'name'`, `'price_desc'`, `'group,date_desc'`). Nested properties with dots are supported (`'user.name'`). The type of each column (string, number, boolean or Date) is detected from the first value that is not null the first time a sort expression is used, and is kept for later sorts with the same expression; strings are compared with diacritics in mind. Passing `true` (or `2`) as the second argument sorts a single property in descending order.

Without `sort` the array of plain values is sorted ascending; `quicksort(true)` sorts it descending. The method returns the same array.

Example: Sort objects
```js
var products = [{ name: 'B', price: 10 }, { name: 'A', price: 20 }];
products.quicksort('name');        // A, B
products.quicksort('price_desc');  // 20, 10
products.quicksort('name', true);  // B, A
[3, 1, 2].quicksort();             // [1, 2, 3]
```

### arr.take(count)

Type: `method`

Returns the first count items as a new array.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `count` | `Number` | yes |  | The number of items. |

Returns: `Array`

Example: Take
```js
[1, 2, 3, 4].take(2);  // [1, 2]
```

### arr.skip(count)

Type: `method`

Returns the items after the first count items as a new array.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `count` | `Number` | yes |  | The number of items to skip. |

Returns: `Array`

Combine with `take()` for paging.

Example: Paging
```js
var page = 2;
var limit = 10;
var items = all.skip((page - 1) * limit).take(limit);
```

### arr.first([def])

Type: `method`

Returns the first item, or a default for an empty array. Array.last() returns the last one.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `def` | `Any` | no |  | The value for an empty array. |

Returns: `Any`

`arr.last([def])` returns the last item or `def`.

Example: First and last
```js
[1, 2].first();     // 1
[].first('none');   // none
[1, 2].last();      // 2
```

### arr.group(name)

Type: `method`

Groups the items by a property.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The property to group by. |

Returns: `Array` Groups `{ name, items }`.

Returns an array of `{ name, items }` sorted by `name`. The value of the property is converted to a string; items without the property are in a group with an empty name.

Example: Group
```js
var items = [{ type: 'x', id: 1 }, { type: 'y', id: 2 }, { type: 'x', id: 3 }];
items.group('type');
// [{ name: 'x', items: [...2 items] }, { name: 'y', items: [...1 item] }]
```

### arr.trim()

Type: `method`

Trims strings and returns a new array without empty values.

Returns: `Array`

Strings in the original array are trimmed in place. The result contains only truthy items, so empty strings, `null`, `undefined`, `0` and `false` are left out.

Example: Clean a list
```js
' a , ,b'.split(',').trim();  // ['a', 'b']
```

### arr.random([item])

Type: `method`

Shuffles the array in place, or returns one random item.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `item` | `Boolean` | no | `false` | Return one random item. |

Returns: `Array|Any`

Without arguments the array is shuffled (Fisher-Yates) and returned. With `item` set to `true` one random item is returned and the array is not changed.

Example: Random
```js
var colors = ['red', 'green', 'blue'];
colors.random(true);  // one color
colors.random();      // the shuffled array
```

### arr.wait(onItem, [callback], [thread])

Type: `method`

Processes the items one by one with an asynchronous function.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `onItem` | `Function` | yes |  | `function(item, next)`. |
| `callback` | `Function` | no |  | Called when all items are processed. |
| `thread` | `Number|Boolean` | no | `1` | Parallel items, or `true` to remove items as they are processed. |

Returns: `Array` The array.

`onItem(item, next)` is called for each item; call `next()` to continue with the next item. `callback()` is called when all items are done. `thread` sets how many items run at the same time (1 by default). With `thread` set to `true` the items are removed from the array with `shift()` as they are processed. Call `next('cancel')` to stop: `callback('cancel')` is then called.

Example: Process in sequence
```js
var ids = [1, 2, 3];
ids.wait(function(id, next) {
	FUNC.removeuser(id, next);
}, function() {
	console.log('All removed');
});
```

Example: Two at a time
```js
urls.wait(function(url, next) {
	REQUEST({ url: url, callback: () => next() });
}, () => console.log('done'), 2);
```

### arr.async([thread], [callback])

Type: `method`

Runs an array of functions one after another.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `thread` | `Number` | no | `1` | How many functions run at the same time. |
| `callback` | `Function` | no |  | Called at the end. |

Returns: `Array` The array.

Each item is a function `(next)`; call `next()` when it finishes. The functions are removed from the array as they run, so the array is empty at the end. `thread` sets how many functions start at the same time (1 by default). `callback()` is called when all functions are done, or `callback('cancel')` when one calls `next('cancel')`.

Example: Run tasks
```js
var tasks = [];
tasks.push(function(next) {
	console.log('first');
	next();
});
tasks.push(function(next) {
	setTimeout(next, 100);
});
tasks.async(function() {
	console.log('done');
});
```

### arr.limit(max, fn, [callback])

Type: `method`

Processes the array in chunks of max items.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `max` | `Number` | yes |  | The size of a chunk. |
| `fn` | `Function` | yes |  | `function(items, next, beg, end)`. |
| `callback` | `Function` | no |  | Called at the end. |

Returns: `Array` The array.

`fn(items, next, beg, end)` receives the next chunk and the start and end index; call `next()` to continue. `callback()` is called after the last chunk.

Example: Insert in batches
```js
rows.limit(100, function(items, next) {
	FUNC.importrows(items, next);
}, function() {
	console.log('Imported');
});
```
