---
title: "Functions"
description: "Reference for every @vinicunca/perkakas export, grouped by category, generated from the package JSDoc."
canonical_url: "https://vinicunca.dev/perkakas/functions"
---
# Functions

> Reference for every @vinicunca/perkakas export, grouped by category, generated from the package JSDoc.

Each card is one export. **Strict**, **Indexed**, and **Lazy** badges come from the JSDoc tags on that function. Lazy helpers can short-circuit inside [`pipe`](#pipe). Signatures list data-first, then data-last. Open **Parameters** for arguments and the return type. The GitHub button jumps to the tagged source for this installed version.

@vinicunca/perkakas 1.19.1. One heading per export, grouped by category.

## Array

### allPass

Determines whether all predicates return true for the input data.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/all-pass.ts#L19>

**Data First**

```ts
allPass(data, fns)
```

**Parameters**

- `data`: The input data for predicates.
- `fns`: The list of predicates.

**Returns** `boolean`

**Example**

```ts
const isDivisibleBy3 = (x: number) => x % 3 === 0;
const isDivisibleBy4 = (x: number) => x % 4 === 0;
const fns = [isDivisibleBy3, isDivisibleBy4];
allPass(12, fns); // => true
allPass(8, fns); // => false
```

**Data Last**

```ts
allPass(fns)(data)
```

**Parameters**

- `fns`: The list of predicates.

**Returns** `Function`

**Example**

```ts
const isDivisibleBy3 = (x: number) => x % 3 === 0;
const isDivisibleBy4 = (x: number) => x % 4 === 0;
const fns = [isDivisibleBy3, isDivisibleBy4];
allPass(fns)(12); // => true
allPass(fns)(8); // => false
```

### anyPass

Determines whether any predicate returns true for the input data.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/any-pass.ts#L19>

**Data First**

```ts
anyPass(data, fns)
```

**Parameters**

- `data`: The input data for predicates.
- `fns`: The list of predicates.

**Returns** `boolean`

**Example**

```ts
const isDivisibleBy3 = (x: number) => x % 3 === 0;
const isDivisibleBy4 = (x: number) => x % 4 === 0;
const fns = [isDivisibleBy3, isDivisibleBy4];
anyPass(8, fns); // => true
anyPass(11, fns); // => false
```

**Data Last**

```ts
anyPass(fns)(data)
```

**Parameters**

- `fns`: The list of predicates.

**Returns** `Function`

**Example**

```ts
const isDivisibleBy3 = (x: number) => x % 3 === 0;
const isDivisibleBy4 = (x: number) => x % 4 === 0;
const fns = [isDivisibleBy3, isDivisibleBy4];
anyPass(fns)(8); // => true
anyPass(fns)(11); // => false
```

### chunk

Split an array into groups the length of `size`. If `array` can't be split evenly, the final chunk will be the remaining elements.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/chunk.ts#L207>

**Data First**

```ts
chunk(array, size)
```

**Parameters**

- `array`: The array.
- `size`: The length of the chunk.

**Returns** `Object`

**Example**

```ts
chunk(['a', 'b', 'c', 'd'], 2); // => [['a', 'b'], ['c', 'd']]
chunk(['a', 'b', 'c', 'd'], 3); // => [['a', 'b', 'c'], ['d']]
```

**Data Last**

```ts
chunk(size)(array)
```

**Parameters**

- `size`: The length of the chunk.

**Returns** `Function`

**Example**

```ts
chunk(2)(['a', 'b', 'c', 'd']); // => [['a', 'b'], ['c', 'd']]
chunk(3)(['a', 'b', 'c', 'd']); // => [['a', 'b', 'c'], ['d']]
```

### concat

Merge two or more arrays. This method does not change the existing arrays,
but instead returns a new array, even if the other array is empty.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/concat.ts#L21>

**Data First**

```ts
concat(data, other)
```

**Parameters**

- `data`: The first items, these would be at the beginning of the new
array.
- `other`: The remaining items, these would be at the end of the new
array.

**Returns** `Array` — A new array with the items of the first array followed by the items
of the second array.

**Example**

```ts
concat([1, 2, 3], ['a']); // [1, 2, 3, 'a']
```

**Data Last**

```ts
concat(arr2)(arr1)
```

**Parameters**

- `other`: The remaining items, these would be at the end of the new
array.

**Returns** `Function` — A new array with the items of the first array followed by the items
of the second array.

**Example**

```ts
concat(['a'])([1, 2, 3]); // [1, 2, 3, 'a']
```

### countBy

Categorize and count elements in an array using a defined callback function.
The callback function is applied to each element in the array to determine
its category and then counts how many elements fall into each category.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/count-by.ts#L21>

**Data First**

```ts
countBy(data, categorizationFn)
```

**Parameters**

- `data`: The array.
- `categorizationFn`: The categorization function.

**Returns** `Object`

**Example**

```ts
countBy(['a', 'b', 'c', 'B', 'A', 'a'], toLowerCase()); //=> { a: 3, b: 2, c: 1 }
```

**Data Last**

```ts
countBy(categorizationFn)(data)
```

**Parameters**

- `categorizationFn`: The categorization function.

**Returns** `Function`

**Example**

```ts
pipe(['a', 'b', 'c', 'B', 'A', 'a'], countBy(toLowerCase())); //=> { a: 3, b: 2, c: 1 }
```

### difference (lazy)

Excludes the values from `other` array. The output maintains the same order
as the input. The inputs are treated as multi-sets/bags (multiple copies of
items are treated as unique items).

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/difference.ts#L21>

**Data First**

```ts
difference(data, other)
```

**Parameters**

- `data`: The input items.
- `other`: The values to exclude.

**Returns** `Array`

**Example**

```ts
difference([1, 2, 3, 4], [2, 5, 3]); // => [1, 4]
difference([1, 1, 2, 2], [1]); // => [1, 2, 2]
```

**Data Last**

```ts
difference(other)(data)
```

**Parameters**

- `other`: The values to exclude.

**Returns** `Function`

**Example**

```ts
pipe([1, 2, 3, 4], difference([2, 5, 3])); // => [1, 4]
pipe([1, 1, 2, 2], difference([1])); // => [1, 2, 2]
```

### differenceWith (lazy)

Excludes the values from `other` array.
Elements are compared by custom comparator isEquals.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/difference-with.ts#L26>

**Data First**

```ts
differenceWith(data, other, isEqual)
```

**Parameters**

- `data`: The source array.
- `other`: The values to exclude.
- `isEqual`: The comparator.

**Returns** `Array`

**Example**

```ts
differenceWith(
  [{ a: 1 }, { a: 2 }, { a: 3 }, { a: 4 }],
  [2, 5, 3],
  ({ a }, b) => a === b,
); //=> [{ a: 1 }, { a: 4 }]
```

**Data Last**

```ts
differenceWith(other, isEqual)(data)
```

**Parameters**

- `other`: The values to exclude.
- `isEqual`: The comparator.

**Returns** `Function`

**Example**

```ts
pipe(
  [{ a: 1 }, { a: 2 }, { a: 3 }, { a: 4 }, { a: 5 }, { a: 6 }],
  differenceWith([2, 3], ({ a }, b) => a === b),
); //=> [{ a: 1 }, { a: 4 }, { a: 5 }, { a: 6 }]
```

### drop (lazy)

Removes first `n` elements from the `array`.

Related operations:
- [`dropLast`](#dropLast) - same, but from the end of the array.
- [`splice`](#splice) - to remove or insert at an arbitrary index.
- [`take`](#take) - to keep the first `n` instead.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/drop.ts#L114>

**Data First**

```ts
drop(array, n)
```

**Parameters**

- `array`: The target array.
- `n`: The number of elements to skip.

**Returns** `Object`

**Example**

```ts
drop([1, 2, 3, 4, 5], 2); // => [3, 4, 5]
```

**Data Last**

```ts
drop(n)(array)
```

**Parameters**

- `n`: The number of elements to skip.

**Returns** `Function`

**Example**

```ts
drop(2)([1, 2, 3, 4, 5]); // => [3, 4, 5]
```

### dropFirstBy

Drop the first `n` items from `data` based on the provided ordering criteria. This allows you to avoid sorting the array before dropping the items. The complexity of this function is *O(Nlogn)* where `N` is the length of the array.

For the opposite operation (to keep `n` elements) see [`takeFirstBy`](#takeFirstBy).

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/drop-first-by.ts#L26>

**Data First**

```ts
dropFirstBy(data, n, ...rules)
```

**Parameters**

- `data`: The input array.
- `n`: The number of items to drop. If `n` is non-positive no items would be dropped and a *clone* of the input would be returned, if `n` is bigger then data.length no items would be returned.
- `...rules`: A variadic array of order rules defining the sorting criteria. Each order rule is a projection function that extracts a comparable value from the data. Sorting is based on these extracted values using the native `<` and `>` operators. Earlier rules take precedence over later ones. Use the syntax `[projection, "desc"]` for descending order.

**Returns** `Array` — A subset of the input array.

**Example**

```ts
dropFirstBy(['aa', 'aaaa', 'a', 'aaa'], 2, (x) => x.length); // => ['aaaa', 'aaa']
```

**Data Last**

```ts
dropFirstBy(n, ...rules)(data)
```

**Parameters**

- `n`: The number of items to drop. If `n` is non-positive no items would be dropped and a *clone* of the input would be returned, if `n` is bigger then data.length no items would be returned.
- `...rules`: A variadic array of order rules defining the sorting criteria. Each order rule is a projection function that extracts a comparable value from the data. Sorting is based on these extracted values using the native `<` and `>` operators. Earlier rules take precedence over later ones. Use the syntax `[projection, "desc"]` for descending order.

**Returns** `Function` — A subset of the input array.

**Example**

```ts
pipe(
  ['aa', 'aaaa', 'a', 'aaa'],
  dropFirstBy(2, (x) => x.length),
); // => ['aaaa', 'aaa']
```

### dropLast

Removes last `n` elements from the `array`.

Related operations:
- [`drop`](#drop) - same, but from the start of the array.
- [`splice`](#splice) - to remove or insert at an arbitrary index.
- [`takeLast`](#takeLast) - to keep the last `n` instead.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/drop-last.ts#L21>

**Data First**

```ts
dropLast(array, n)
```

**Parameters**

- `array`: The target array.
- `n`: The number of elements to skip.

**Returns** `Array`

**Example**

```ts
dropLast([1, 2, 3, 4, 5], 2); // => [1, 2, 3]
```

**Data Last**

```ts
dropLast(n)(array)
```

**Parameters**

- `n`: The number of elements to skip.

**Returns** `Function`

**Example**

```ts
dropLast(2)([1, 2, 3, 4, 5]); // => [1, 2, 3]
```

### dropLastWhile

Removes elements from the end of the array until the predicate returns false.

The predicate is applied to each element in the array starting from the end and moving towards the beginning, until the predicate returns false. The returned array includes elements from the beginning of the array, up to and including the element that produced false for the predicate.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/drop-last-while.ts#L18>

**Data First**

```ts
dropLastWhile(data, predicate)
```

**Parameters**

- `data`: The array.
- `predicate`: The predicate.

**Returns** `Array`

**Example**

```ts
dropLastWhile([1, 2, 10, 3, 4], (x) => x < 10); // => [1, 2, 10]
```

**Data Last**

```ts
dropLastWhile(predicate)(data)
```

**Parameters**

- `predicate`: The predicate.

**Returns** `Function`

**Example**

```ts
pipe(
  [1, 2, 10, 3, 4],
  dropLastWhile((x) => x < 10),
); // => [1, 2, 10]
```

### dropWhile

Removes elements from the beginning of the array until the predicate returns false.

The predicate is applied to each element in the array, until the predicate returns false. The returned array includes the rest of the elements, starting with the element that produced false for the predicate.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/drop-while.ts#L18>

**Data First**

```ts
dropWhile(data, predicate)
```

**Parameters**

- `data`: The array.
- `predicate`: The predicate.

**Returns** `Array`

**Example**

```ts
dropWhile([1, 2, 10, 3, 4], (x) => x < 10); // => [10, 3, 4]
```

**Data Last**

```ts
dropWhile(predicate)(data)
```

**Parameters**

- `predicate`: The predicate.

**Returns** `Function`

**Example**

```ts
pipe(
  [1, 2, 10, 3, 4],
  dropWhile((x) => x < 10),
); // => [10, 3, 4]
```

### filter (lazy)

Creates a shallow copy of a portion of a given array, filtered down to just
the elements from the given array that pass the test implemented by the
provided function. Equivalent to `Array.prototype.filter`.

Related operations:
- [`splice`](#splice) - to shape the array by *position* rather than by *value*.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/filter.ts#L35>

**Data First**

```ts
filter(data, predicate)
```

**Parameters**

- `data`: The array to filter.
- `predicate`: A function to execute for each element in the array. It
should return `true` to keep the element in the resulting array, and `false`
otherwise. A type-predicate can also be used to narrow the result.

**Returns** `Object` — A shallow copy of the given array containing just the elements that
pass the test. If no elements pass the test, an empty array is returned.

**Example**

```ts
filter([1, 2, 3], (x) => x % 2 === 1); // => [1, 3]
```

**Data Last**

```ts
filter(predicate)(data)
```

**Parameters**

- `predicate`: A function to execute for each element in the array. It
should return `true` to keep the element in the resulting array, and `false`
otherwise. A type-predicate can also be used to narrow the result.

**Returns** `Function` — A shallow copy of the given array containing just the elements that
pass the test. If no elements pass the test, an empty array is returned.

**Example**

```ts
pipe(
  [1, 2, 3],
  filter((x) => x % 2 === 1),
); // => [1, 3]
```

### find (lazy)

Returns the first element in the provided array that satisfies the provided
testing function. If no values satisfy the testing function, `undefined` is
returned.

Similar functions:
[`findLast`](#findLast) - If you need the last element that satisfies the provided testing function.
[`findIndex`](#findIndex) - If you need the index of the found element in the array.
`indexOf` - If you need to find the index of a value.
`includes` - If you need to find if a value exists in an array.
`some` - If you need to find if any element satisfies the provided testing function.
[`filter`](#filter) - If you need to find all elements that satisfy the provided testing function.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/find.ts#L106>

**Data First**

```ts
find(data, predicate)
```

**Parameters**

- `data`: The items to search in.
- `predicate`: A function to execute for each element in the array. It
should return `true` to indicate a matching element has been found, and
`false` otherwise. A type-predicate can also be used to narrow the result.

**Returns** `Object` — The first element in the array that satisfies the provided testing
function. Otherwise, `undefined` is returned.

**Example**

```ts
find([1, 3, 4, 6], (n) => n % 2 === 0); // => 4
```

**Data Last**

```ts
find(predicate)(data)
```

**Parameters**

- `predicate`: A function to execute for each element in the array. It
should return `true` to indicate a matching element has been found, and
`false` otherwise. A type-predicate can also be used to narrow the result.

**Returns** `Function` — The first element in the array that satisfies the provided testing
function. Otherwise, `undefined` is returned.

**Example**

```ts
pipe(
  [1, 3, 4, 6],
  find((n) => n % 2 === 0),
); // => 4
```

### findIndex

Returns the index of the first element in an array that satisfies the
provided testing function. If no elements satisfy the testing function, -1 is
returned.

See also the [`find`](#find) method, which returns the first element that satisfies
the testing function (rather than its index).

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/find-index.ts#L24>

**Data First**

```ts
findIndex(data, predicate)
```

**Parameters**

- `data`: The items to search in.
- `predicate`: A function to execute for each element in the array. It
should return a `true` to indicate a matching element has been found, and a
`false` otherwise.

**Returns** `number` — The index of the first element in the array that passes the test.
Otherwise, -1.

**Example**

```ts
findIndex([1, 3, 4, 6], (n) => n % 2 === 0); // => 2
```

**Data Last**

```ts
findIndex(predicate)(data)
```

**Parameters**

- `predicate`: A function to execute for each element in the array. It
should return a `true` to indicate a matching element has been found, and a
`false` otherwise.

**Returns** `Function` — The index of the first element in the array that passes the test.
Otherwise, -1.

**Example**

```ts
pipe(
  [1, 3, 4, 6],
  findIndex((n) => n % 2 === 0),
); // => 2
```

### findLast

Iterates the array in reverse order and returns the value of the first
element that satisfies the provided testing function. If no elements satisfy
the testing function, undefined is returned.

Similar functions:
[`find`](#find) - If you need the first element that satisfies the provided testing function.
[`findLastIndex`](#findLastIndex) - If you need the index of the found element in the array.
`lastIndexOf` - If you need to find the index of a value.
`includes` - If you need to find if a value exists in an array.
`some` - If you need to find if any element satisfies the provided testing function.
[`filter`](#filter) - If you need to find all elements that satisfy the provided testing function.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/find-last.ts#L97>

**Data First**

```ts
findLast(data, predicate)
```

**Parameters**

- `data`: The items to search in.
- `predicate`: A function to execute for each element in the array. It
should return `true` to indicate a matching element has been found, and
`false` otherwise. A type-predicate can also be used to narrow the result.

**Returns** `Object` — The last (highest-index) element in the array that satisfies the
provided testing function; undefined if no matching element is found.

**Example**

```ts
findLast([1, 3, 4, 6], (n) => n % 2 === 1); // => 3
```

**Data Last**

```ts
findLast(predicate)(data)
```

**Parameters**

- `predicate`: A function to execute for each element in the array. It
should return `true` to indicate a matching element has been found, and
`false` otherwise. A type-predicate can also be used to narrow the result.

**Returns** `Function` — The last (highest-index) element in the array that satisfies the
provided testing function; undefined if no matching element is found.

**Example**

```ts
pipe(
  [1, 3, 4, 6],
  findLast((n) => n % 2 === 1),
); // => 3
```

### findLastIndex

Iterates the array in reverse order and returns the index of the first
element that satisfies the provided testing function. If no elements satisfy
the testing function, -1 is returned.

See also [`findLast`](#findLast) which returns the value of last element that satisfies
the testing function (rather than its index).

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/find-last-index.ts#L24>

**Data First**

```ts
findLastIndex(data, predicate)
```

**Parameters**

- `data`: The items to search in.
- `predicate`: A function to execute for each element in the array. It
should return `true` to indicate a matching element has been found, and
`false` otherwise.

**Returns** `number` — The index of the last (highest-index) element in the array that
passes the test. Otherwise -1 if no matching element is found.

**Example**

```ts
findLastIndex([1, 3, 4, 6], (n) => n % 2 === 1); // => 1
```

**Data Last**

```ts
findLastIndex(fn)(items)
```

**Parameters**

- `predicate`: A function to execute for each element in the array. It
should return `true` to indicate a matching element has been found, and
`false` otherwise.

**Returns** `Function` — The index of the last (highest-index) element in the array that
passes the test. Otherwise -1 if no matching element is found.

**Example**

```ts
pipe(
  [1, 3, 4, 6],
  findLastIndex((n) => n % 2 === 1),
); // => 1
```

### first (lazy)

Gets the first element of `array`.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/first.ts#L25>

**Data First**

```ts
first(array)
```

**Parameters**

- `data`: The array.

**Returns** `Object` — The first element of the array.

**Example**

```ts
first([1, 2, 3]); // => 1
first([]); // => undefined
```

**Data Last**

```ts
first()(array)
```

**Returns** `Function` — The first element of the array.

**Example**

```ts
pipe(
  [1, 2, 4, 8, 16],
  filter((x) => x > 3),
  first(),
  (x) => x + 1,
); // => 5
```

### firstBy

Find the first element in the array that adheres to the order rules provided. This is a superset of what a typical `maxBy` or `minBy` function would do as it allows defining "tie-breaker" rules when values are equal, and allows comparing items using any logic. This function is equivalent to calling `first(sortBy(...))` but runs at *O(n)* instead of *O(nlogn)*.

Use [`nthBy`](#nthBy) if you need an element other that the first, or [`takeFirstBy`](#takeFirstBy) if you more than just the first element.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/first-by.ts#L40>

**Data First**

```ts
firstBy(data, ...rules)
```

**Parameters**

- `data`: An array of items.
- `...rules`: A variadic array of order rules defining the sorting criteria. Each order rule is a projection function that extracts a comparable value from the data. Sorting is based on these extracted values using the native `<` and `>` operators. Earlier rules take precedence over later ones. Use the syntax `[projection, "desc"]` for descending order.

**Returns** `Object` — The first element by the order criteria, or `undefined` if the array
is empty. (The function provides strong typing if the input type assures the
array isn't empty).

**Example**

```ts
const max = firstBy([1, 2, 3], [identity(), 'desc']); // => 3;
const min = firstBy([1, 2, 3], identity()); // => 1;

const data = [{ a: 'a' }, { a: 'aa' }, { a: 'aaa' }] as const;
const maxBy = firstBy(data, [(item) => item.a.length, 'desc']); // => { a: "aaa" };
const minBy = firstBy(data, (item) => item.a.length); // => { a: "a" };

const data = [
  { type: 'cat', size: 1 },
  { type: 'cat', size: 2 },
  { type: 'dog', size: 3 },
] as const;
const multi = firstBy(data, prop('type'), [prop('size'), 'desc']); // => {type: "cat", size: 2}
```

**Data Last**

```ts
firstBy(...rules)(data)
```

**Parameters**

- `...rules`: A variadic array of order rules defining the sorting criteria. Each order rule is a projection function that extracts a comparable value from the data. Sorting is based on these extracted values using the native `<` and `>` operators. Earlier rules take precedence over later ones. Use the syntax `[projection, "desc"]` for descending order.

**Returns** `Function` — The first element by the order criteria, or `undefined` if the array
is empty. (The function provides strong typing if the input type assures the
array isn't empty).

**Example**

```ts
const max = pipe([1, 2, 3], firstBy([identity(), 'desc'])); // => 3;
const min = pipe([1, 2, 3], firstBy(identity())); // => 1;

const data = [{ a: 'a' }, { a: 'aa' }, { a: 'aaa' }] as const;
const maxBy = pipe(data, firstBy([(item) => item.a.length, 'desc'])); // => { a: "aaa" };
const minBy = pipe(
  data,
  firstBy((item) => item.a.length),
); // => { a: "a" };

const data = [
  { type: 'cat', size: 1 },
  { type: 'cat', size: 2 },
  { type: 'dog', size: 3 },
] as const;
const multi = pipe(data, firstBy(prop('type'), [prop('size'), 'desc'])); // => {type: "cat", size: 2}
```

### flat (lazy)

Creates a new array with all sub-array elements concatenated into it
recursively up to the specified depth. Equivalent to the built-in
`Array.prototype.flat` method.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/flat.ts#L83>

**Data First**

```ts
flat(data)
flat(data, depth)
```

**Parameters**

- `data`: The items to flatten.
- `depth` (optional): The depth level specifying how deep a nested array structure
should be flattened. Defaults to 1. Non literal values (those typed as
`number`cannot be used. `Infinity`, `Number.POSITIVE_INFINITY` and
`Number.MAX_VALUE` are all typed as `number` and can't be used either. For
"unlimited" depth use a literal value that would exceed your expected
practical maximum nesting level.

**Returns** `Object`

**Example**

```ts
flat([[1, 2], [3, 4], [5], [[6]]]); // => [1, 2, 3, 4, 5, [6]]
flat([[[1]], [[2]]], 2); // => [1, 2]
```

**Data Last**

```ts
flat()(data)
flat(depth)(data)
```

**Parameters**

- `depth` (optional): The depth level specifying how deep a nested array structure
should be flattened. Defaults to 1.

**Returns** `Function`

**Example**

```ts
pipe([[1, 2], [3, 4], [5], [[6]]], flat()); // => [1, 2, 3, 4, 5, [6]]
pipe([[[1]], [[2]]], flat(2)); // => [1, 2]
```

### flatMap (lazy)

Returns a new array formed by applying a given callback function to each
element of the array, and then flattening the result by one level. It is
identical to a [`map`](#map) followed by a [`flat`](#flat) of depth 1
(`flat(map(data, ...args))`), but slightly more efficient than calling those
two methods separately. Equivalent to `Array.prototype.flatMap`.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/flat-map.ts#L29>

**Data First**

```ts
flatMap(data, callbackfn)
```

**Parameters**

- `data`: The items to map and flatten.
- `callbackfn`: A function to execute for each element in the array. It
should return an array containing new elements of the new array, or a single
non-array value to be added to the new array.

**Returns** `Array` — A new array with each element being the result of the callback
function and flattened by a depth of 1.

**Example**

```ts
flatMap([1, 2, 3], (x) => [x, x * 10]); // => [1, 10, 2, 20, 3, 30]
```

**Data Last**

```ts
flatMap(callbackfn)(data)
```

**Parameters**

- `callbackfn`: A function to execute for each element in the array. It
should return an array containing new elements of the new array, or a single
non-array value to be added to the new array.

**Returns** `Function` — A new array with each element being the result of the callback
function and flattened by a depth of 1.

**Example**

```ts
pipe(
  [1, 2, 3],
  flatMap((x) => [x, x * 10]),
); // => [1, 10, 2, 20, 3, 30]
```

### forEach (lazy)

Executes a provided function once for each array element. Equivalent to
`Array.prototype.forEach`.

The dataLast version returns the original array (instead of not returning
anything (`void`)) to allow using it in a pipe. When not used in a [`pipe`](#pipe) the
returned array is equal to the input array (by reference), and not a shallow
copy of it!

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/for-each.ts#L29>

**Data First**

```ts
forEach(data, callbackfn)
```

**Parameters**

- `data`: The values that would be iterated on.
- `callbackfn`: A function to execute for each element in the array.

**Returns** `void`

**Example**

```ts
forEach([1, 2, 3], (x) => {
  console.log(x);
});
```

**Data Last**

```ts
forEach(callbackfn)(data)
```

**Parameters**

- `callbackfn`: A function to execute for each element in the array.

**Returns** `Function` — The original array (the ref itself, not a shallow copy of it).

**Example**

```ts
pipe(
  [1, 2, 3],
  forEach((x) => {
    console.log(x);
  }),
); // => [1, 2, 3]
```

### groupBy

Groups the elements of a given iterable according to the string values
returned by a provided callback function. The returned object has separate
properties for each group, containing arrays with the elements in the group.
Unlike the built in `Object.groupBy` this function also allows the callback to
return `undefined` in order to exclude the item from being added to any
group.

If you are grouping objects by a property of theirs (e.g.
`groupBy(data, ({ myProp }) => myProp)` or `groupBy(data, prop('myProp'))`)
consider using [`groupByProp`](#groupByProp) (e.g. `groupByProp(data, 'myProp')`) instead,
as it would provide better typing.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/group-by.ts#L32>

**Data First**

```ts
groupBy(data, callbackfn)
```

**Parameters**

- `data`: The items to group.
- `callbackfn`: A function to execute for each element in the iterable.
It should return a value indicating the group of the current element, or
`undefined` when the item should be excluded from any group.

**Returns** `Object` — An object with properties for all groups, each assigned to an array
containing the elements of the associated group.

**Example**

```ts
groupBy([{ a: 'cat' }, { a: 'dog' }] as const, prop('a')); // => {cat: [{a: 'cat'}], dog: [{a: 'dog'}]}
groupBy([0, 1], (x) => (x % 2 === 0 ? 'even' : undefined)); // => {even: [0]}
```

**Data Last**

```ts
groupBy(callbackfn)(data)
```

**Parameters**

- `callbackfn`: A function to execute for each element in the iterable.
It should return a value indicating the group of the current element, or
`undefined` when the item should be excluded from any group.

**Returns** `Function` — An object with properties for all groups, each assigned to an array
containing the elements of the associated group.

**Example**

```ts
pipe([{ a: 'cat' }, { a: 'dog' }] as const, groupBy(prop('a'))); // => {cat: [{a: 'cat'}], dog: [{a: 'dog'}]}
pipe(
  [0, 1],
  groupBy((x) => (x % 2 === 0 ? 'even' : undefined)),
); // => {even: [0]}
```

### groupByProp

Groups the elements of an array of objects based on the values of a
specified property of those objects. The result would contain a property for
each unique value of the specific property, with it's value being the input
array filtered to only items that have that property set to that value.
For any object where the property is missing, or if it's value is
`undefined` the item would be filtered out.

The grouping property is enforced at the type level to exist in at least one
item and to never have a value that cannot be used as an object key (e.g. it
must be `PropertyKey | undefined`).

The resulting arrays are filtered with the prop and it's value as a
type-guard, effectively narrowing the items in each output arrays. This
means that when the grouping property is the discriminator of a
discriminated union type each output array would contain just the subtype for
that value.

If you need more control over the grouping you should use [`groupBy`](#groupBy) instead.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/group-by-prop.ts#L140>

**Data First**

```ts
groupByProp(data, prop)
```

**Parameters**

- `data`: The items to group.
- `prop`: The property name to group by.

**Returns** `Object`

**Example**

```ts
const result = groupByProp(
  //  ^? { cat: [{ a: 'cat' }], dog: [{ a: 'dog' }] }
  [{ a: 'cat' }, { a: 'dog' }] as const,
  'a',
);
```

**Data Last**

```ts
groupByProp(prop)(data)
```

**Parameters**

- `prop`: The property name to group by.

**Returns** `Function`

**Example**

```ts
const result = pipe(
  //  ^? { cat: [{ a: 'cat' }], dog: [{ a: 'dog' }] }
  [{ a: 'cat' }, { a: 'dog' }] as const,
  groupByProp('a'),
);
```

### hasAtLeast

Checks if the given array has at least the defined number of elements. When
the minimum used is a literal (e.g. `3`) the output is refined accordingly so
that those indices are defined when accessing the array even when using
typescript's 'noUncheckedIndexAccess'.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/has-at-least.ts#L28>

**Data First**

```ts
hasAtLeast(data, minimum)
```

**Parameters**

- `data`: The input array.
- `minimum`: The minimum number of elements the array must have.

**Returns** `boolean` — True if the array's length is *at least* `minimum`. When `minimum`
is a literal value, the output is narrowed to ensure the first items are
guaranteed.

**Example**

```ts
hasAtLeast([], 4); // => false

const data: number[] = [1, 2, 3, 4];
hasAtLeast(data, 1); // => true
data[0]; // 1, with type `number`
```

**Data Last**

```ts
hasAtLeast(minimum)(data)
```

**Parameters**

- `minimum`: The minimum number of elements the array must have.

**Returns** `Function` — True if the array's length is *at least* `minimum`. When `minimum`
is a literal value, the output is narrowed to ensure the first items are
guaranteed.

**Example**

```ts
pipe([], hasAtLeast(4)); // => false

const data = [[1, 2], [3], [4, 5]];
pipe(
  data,
  filter(hasAtLeast(2)),
  map(([, second]) => second),
); // => [2,5], with type `number[]`
```

### indexBy

Converts a list of objects into an object indexing the objects by the given
key.

There are several other functions that could be used to build an object from
an array:
[`fromKeys`](#fromKeys) - Builds an object from an array of *keys* and a mapper for values.
[`pullObject`](#pullObject) - Builds an object from an array of items with mappers for *both* keys and values.
[`fromEntries`](#fromEntries) - Builds an object from an array of key-value pairs.
Refer to the docs for more details.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/index-by.ts#L24>

**Data First**

```ts
indexBy(array, fn)
```

**Parameters**

- `data`: The array.
- `mapper`: The indexing function.

**Returns** `Object`

**Example**

```ts
indexBy(['one', 'two', 'three'], (x) => x.length); // => {3: 'two', 5: 'three'}
```

**Data Last**

```ts
indexBy(fn)(array)
```

**Parameters**

- `mapper`: The indexing function.

**Returns** `Function`

**Example**

```ts
pipe(
  ['one', 'two', 'three'],
  indexBy((x) => x.length),
); // => {3: 'two', 5: 'three'}
```

### intersection (lazy)

Returns a list of elements that exist in both array. The output maintains the
same order as the input. The inputs are treated as multi-sets/bags (multiple
copies of items are treated as unique items).

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/intersection.ts#L27>

**Data First**

```ts
intersection(data, other)
```

**Parameters**

- `data`: The input items.
- `other`: The items to compare against.

**Returns** `Array`

**Example**

```ts
intersection([1, 2, 3], [2, 3, 5]); // => [2, 3]
intersection([1, 1, 2, 2], [1]); // => [1]
```

**Data Last**

```ts
intersection(other)(data)
```

**Parameters**

- `other`: The items to compare against.

**Returns** `Function`

**Example**

```ts
pipe([1, 2, 3], intersection([2, 3, 5])); // => [2, 3]
pipe([1, 1, 2, 2], intersection([1])); // => [1]
```

### intersectionWith (lazy)

Returns a list of intersecting values based on a custom
comparator function that compares elements of both arrays.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/intersection-with.ts#L29>

**Data First**

```ts
intersectionWith(data, other, isEqual)
```

**Parameters**

- `data`: The source data.
- `other`: The other data.
- `isEqual`: The custom comparator.

**Returns** `Array`

**Example**

```ts
intersectionWith(
  [
    { id: 1, name: 'Ryan' },
    { id: 3, name: 'Emma' },
  ],
  [3, 5],
  (a, b) => a.id === b,
); // => [{ id: 3, name: 'Emma' }]
```

**Data Last**

```ts
intersectionWith(other, isEqual)(data)
```

**Parameters**

- `other`: The other data.
- `isEqual`: The custom comparator.

**Returns** `Function`

**Example**

```ts
intersectionWith(
  [3, 5],
  (a, b) => a.id === b,
)([
  { id: 1, name: 'Ryan' },
  { id: 3, name: 'Emma' },
]); // => [{ id: 3, name: 'Emma' }]
```

### join

Joins the elements of the array by: casting them to a string and
concatenating them one to the other, with the provided glue string in between
every two elements.

When called on a tuple and with stricter item types (union of literal values,
the result is strictly typed to the tuples shape and it's item types).

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/join.ts#L26>

**Data First**

```ts
join(data, glue)
```

**Parameters**

- `data`: The array to join.
- `glue`: The string to put in between every two elements.

**Returns** `Object`

**Example**

```ts
join([1, 2, 3], ','); // => "1,2,3" (typed `string`)
join(['a', 'b', 'c'], ''); // => "abc" (typed `string`)
join(['hello', 'world'] as const, ' '); // => "hello world" (typed `hello world`)
```

**Data Last**

```ts
join(glue)(data)
```

**Parameters**

- `glue`: The string to put in between every two elements.

**Returns** `Function`

**Example**

```ts
pipe([1, 2, 3], join(',')); // => "1,2,3" (typed `string`)
pipe(['a', 'b', 'c'], join('')); // => "abc" (typed `string`)
pipe(['hello', 'world'] as const, join(' ')); // => "hello world" (typed `hello world`)
```

### last

Gets the last element of `array`.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/last.ts#L17>

**Data First**

```ts
last(array)
```

**Parameters**

- `data`: The array.

**Returns** `Object`

**Example**

```ts
last([1, 2, 3]); // => 3
last([]); // => undefined
```

**Data Last**

```ts
last()(array)
```

**Returns** `Function`

**Example**

```ts
pipe(
  [1, 2, 4, 8, 16],
  filter((x) => x > 3),
  last(),
  (x) => x + 1,
); // => 17
```

### length

Counts values of the collection or iterable.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/length.ts#L16>

**Data First**

```ts
length(array)
```

**Parameters**

- `items`: The input data.

**Returns** `number`

**Example**

```ts
length([1, 2, 3]); // => 3
```

**Data Last**

```ts
length()(array)
```

**Returns** `Function`

**Example**

```ts
pipe([1, 2, 3], length()); // => 3
```

### map (lazy)

Creates a new array populated with the results of calling a provided function
on every element in the calling array. Equivalent to `Array.prototype.map`.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/map.ts#L27>

**Data First**

```ts
map(data, callbackfn)
```

**Parameters**

- `data`: The array to map.
- `callbackfn`: A function to execute for each element in the array. Its
return value is added as a single element in the new array.

**Returns** `Object` — A new array with each element being the result of the callback
function.

**Example**

```ts
map([1, 2, 3], multiply(2)); // => [2, 4, 6]
map([0, 0], add(1)); // => [1, 1]
map([0, 0], (value, index) => value + index); // => [0, 1]
```

**Data Last**

```ts
map(callbackfn)(data)
```

**Parameters**

- `callbackfn`: A function to execute for each element in the array. Its
return value is added as a single element in the new array.

**Returns** `Function` — A new array with each element being the result of the callback
function.

**Example**

```ts
pipe([1, 2, 3], map(multiply(2))); // => [2, 4, 6]
pipe([0, 0], map(add(1))); // => [1, 1]
pipe(
  [0, 0],
  map((value, index) => value + index),
); // => [0, 1]
```

### mapToObj

Map each element of an array into an object using a defined mapper that
converts each item into an object entry (a tuple of `[<key>, <value>]`).

There are several other functions that could be used to build an object from
an array:
- [`fromKeys`](#fromKeys) - Builds an object from an array of *keys* and a mapper for
values.
- [`indexBy`](#indexBy) - Builds an object from an array of *values* and a mapper for
keys.
- [`pullObject`](#pullObject) - Builds an object from an array of items with a mapper for
values and another mapper for keys.
- [`fromEntries`](#fromEntries) - Builds an object from an array of key-value pairs.

**Warning**: We strongly advise against using this function unless it is
used with a huge input array and your app has stringent memory/gc
constraints. We recommend that in most cases you should use [`pullObject`](#pullObject),
or the composition `fromEntries(map(array, fn))`. This function will be
deprecated and **removed** in future versions of the library!

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/map-to-obj.ts#L34>

**Data First**

```ts
mapToObj(array, fn)
```

**Parameters**

- `array`: The array to map.
- `fn`: The mapping function, which should return a tuple of [key, value], similar to Object.fromEntries.

**Returns** `Record` — The new mapped object.

**Example**

```ts
mapToObj([1, 2, 3], (x) => [String(x), x * 2]); // => {1: 2, 2: 4, 3: 6}
```

**Data Last**

```ts
mapToObj(fn)(array)
```

**Parameters**

- `fn`: The mapping function, which should return a tuple of [key, value], similar to Object.fromEntries.

**Returns** `Function` — The new mapped object.

**Example**

```ts
pipe(
  [1, 2, 3],
  mapToObj((x) => [String(x), x * 2]),
); // => {1: 2, 2: 4, 3: 6}
```

### mapWithFeedback (lazy)

Applies a function on each element of the array, using the result of the
previous application, and returns an array of the successively computed
values.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/map-with-feedback.ts#L38>

**Data First**

```ts
mapWithFeedback(data, callbackfn, initialValue)
```

**Parameters**

- `data`: The array to map over.
- `callbackfn`: The callback function that receives the previous value,
the current element.
- `initialValue`: The initial value to start the computation with.

**Returns** `Object` — An array of successively computed values from the left side of the
array.

**Example**

```ts
mapWithFeedback([1, 2, 3, 4, 5], (prev, x) => prev + x, 100); // => [101, 103, 106, 110, 115]
```

**Data Last**

```ts
mapWithFeedback(callbackfn, initialValue)(data)
```

**Parameters**

- `callbackfn`: The callback function that receives the previous value,
the current element.
- `initialValue`: The initial value to start the computation with.

**Returns** `Function` — An array of successively computed values from the left side of the
array.

**Example**

```ts
pipe(
  [1, 2, 3, 4, 5],
  mapWithFeedback((prev, x) => prev + x, 100),
); // => [101, 103, 106, 110, 115]
```

### meanBy

Returns the mean of the elements of an array using the provided predicate.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/mean-by.ts#L18>

**Data First**

```ts
meanBy(array, fn)
```

**Parameters**

- `items`: The array.
- `fn`: Predicate function.

**Returns** `number`

**Example**

```ts
meanBy([{ a: 5 }, { a: 1 }, { a: 3 }], (x) => x.a); // 3
```

**Data Last**

```ts
meanBy(fn)(array)
```

**Parameters**

- `fn`: Predicate function.

**Returns** `Function`

**Example**

```ts
pipe(
  [{ a: 5 }, { a: 1 }, { a: 3 }],
  meanBy((x) => x.a),
); // 3
```

### mergeAll

Merges a list of objects into a single object.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/merge-all.ts#L54>

**Data First**

```ts
mergeAll(objects)
```

**Parameters**

- `objects`: The array of objects.

**Returns** `Object` — A new object merged with all of the objects in the list. If the list is empty, an empty object is returned.

**Example**

```ts
mergeAll([{ a: 1, b: 1 }, { b: 2, c: 3 }, { d: 10 }]); // => { a: 1, b: 2, c: 3, d: 10 }
mergeAll([]); // => {}
```

### nthBy

Retrieves the element that would be at the given index if the array were sorted according to specified rules. This function uses the *QuickSelect* algorithm running at an average complexity of *O(n)*. Semantically it is equivalent to `sortBy(data, ...rules).at(index)` which would run at *O(nlogn)*.

See also [`firstBy`](#firstBy) which provides an even more efficient algorithm and a stricter return type, but only for `index === 0`. See [`takeFirstBy`](#takeFirstBy) to get all the elements up to and including `index`.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/nth-by.ts#L27>

**Data First**

```ts
nthBy(data, index, ...rules)
```

**Parameters**

- `data`: The input array.
- `index`: The zero-based index for selecting the element in the sorted order. Negative indices count backwards from the end.
- `...rules`: A variadic array of order rules defining the sorting criteria. Each order rule is a projection function that extracts a comparable value from the data. Sorting is based on these extracted values using the native `<` and `>` operators. Earlier rules take precedence over later ones. Use the syntax `[projection, "desc"]` for descending order.

**Returns** `Object | undefined` — The element at the specified index in the sorted order, or `undefined` if the index is out of bounds.

**Example**

```ts
nthBy([2, 1, 4, 5, 3], 2, identity()); // => 3
```

**Data Last**

```ts
nthBy(index, ...rules)(data)
```

**Parameters**

- `index`: The zero-based index for selecting the element in the sorted order. Negative indices count backwards from the end.
- `...rules`: A variadic array of order rules defining the sorting criteria. Each order rule is a projection function that extracts a comparable value from the data. Sorting is based on these extracted values using the native `<` and `>` operators. Earlier rules take precedence over later ones. Use the syntax `[projection, "desc"]` for descending order.

**Returns** `Function` — The element at the specified index in the sorted order, or `undefined` if the index is out of bounds.

**Example**

```ts
pipe([2, 1, 4, 5, 3], nthBy(2, identity())); // => 3
```

### only

Returns the first and only element of `data`, or undefined otherwise.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/only.ts#L27>

**Data First**

```ts
only(data)
```

**Parameters**

- `data`: The target array.

**Returns** `Object`

**Example**

```ts
only([]); // => undefined
only([1]); // => 1
only([1, 2]); // => undefined
```

**Data Last**

```ts
only()(data)
```

**Returns** `Function`

**Example**

```ts
pipe([], only()); // => undefined
pipe([1], only()); // => 1
pipe([1, 2], only()); // => undefined
```

### partition

Splits a collection into two groups, the first of which contains elements the
`predicate` type guard passes, and the second one containing the rest.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/partition.ts#L29>

**Data First**

```ts
partition(data, predicate)
```

**Parameters**

- `data`: The items to split.
- `predicate`: A function to execute for each element in the array. It
should return `true` to add the element to the first partition, and `false`
to add the element to the other partition. A type-predicate can also be used
to narrow the result.

**Returns** `Array` — A 2-tuple of arrays where the first array contains the elements that
passed the predicate, and the second array contains the elements that did
not. The items are in the same order as they were in the original array.

**Example**

```ts
partition(['one', 'two', 'forty two'], (x) => x.length === 3); // => [['one', 'two'], ['forty two']]
```

**Data Last**

```ts
partition(predicate)(data)
```

**Parameters**

- `predicate`: A function to execute for each element in the array. It
should return `true` to add the element to the first partition, and `false`
to add the element to the other partition. A type-predicate can also be used
to narrow the result.

**Returns** `Function` — A 2-tuple of arrays where the first array contains the elements that
passed the predicate, and the second array contains the elements that did
not. The items are in the same order as they were in the original array.

**Example**

```ts
pipe(
  ['one', 'two', 'forty two'],
  partition((x) => x.length === 3),
); // => [['one', 'two'], ['forty two']]
```

### range

Returns a sequence of numbers from `start` (inclusive) to `end` (exclusive),
adding `step` (default is `1`) to each number in the sequence.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/range.ts#L34>

**Data First**

```ts
range(start, end)
range(start, { end, step })
```

**Parameters**

- `start`: The first number in the sequence.
- `endOrOptions`: The end number **or** an object which is used to
**also** define a step size.

**Returns** `Array`

**Example**

```ts
range(1, 5); //=> [1, 2, 3, 4]
range(1, { end: 5, step: 2 }); //=> [1, 3]
```

**Data Last**

```ts
range(end)(start)
range({ end, step })(start)
```

**Parameters**

- `endOrOptions`: The end number **or** an object which is used to
**also** define a step size.

**Returns** `Function`

**Example**

```ts
pipe(1, range(5)); //=> [1, 2, 3, 4]
pipe(1, range({ end: 5, step: 2 })); //=> [1, 3]
```

### rankBy

Calculates the rank of an item in an array based on `rules`. The rank is the position where the item would appear in the sorted array. This function provides an efficient way to determine the rank in *O(n)* time, compared to *O(nlogn)* for the equivalent `sortedIndex(sortBy(data, ...rules), item)`.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/rank-by.ts#L27>

**Data First**

```ts
rankBy(data, item, ...rules)
```

**Parameters**

- `data`: The input array.
- `item`: The item whose rank is to be determined.
- `...rules`: A variadic array of order rules defining the sorting criteria. Each order rule is a projection function that extracts a comparable value from the data. Sorting is based on these extracted values using the native `<` and `>` operators. Earlier rules take precedence over later ones. Use the syntax `[projection, "desc"]` for descending order.

**Returns** `number` — The rank of the item in the sorted array in the range [0..data.length].

**Example**

```ts
const DATA = [{ a: 5 }, { a: 1 }, { a: 3 }] as const;
rankBy(DATA, 0, prop('a')); // => 0
rankBy(DATA, 1, prop('a')); // => 1
rankBy(DATA, 2, prop('a')); // => 1
rankBy(DATA, 3, prop('a')); // => 2
```

**Data Last**

```ts
rankBy(item, ...rules)(data)
```

**Parameters**

- `item`: The item whose rank is to be determined.
- `...rules`: A variadic array of order rules defining the sorting criteria. Each order rule is a projection function that extracts a comparable value from the data. Sorting is based on these extracted values using the native `<` and `>` operators. Earlier rules take precedence over later ones. Use the syntax `[projection, "desc"]` for descending order.

**Returns** `Function` — The rank of the item in the sorted array in the range [0..data.length].

**Example**

```ts
const DATA = [{ a: 5 }, { a: 1 }, { a: 3 }] as const;
pipe(DATA, rankBy(0, prop('a'))); // => 0
pipe(DATA, rankBy(1, prop('a'))); // => 1
pipe(DATA, rankBy(2, prop('a'))); // => 1
pipe(DATA, rankBy(3, prop('a'))); // => 2
```

### reduce

Executes a user-supplied "reducer" callback function on each element of the
array, in order, passing in the return value from the calculation on the
preceding element. The final result of running the reducer across all
elements of the array is a single value. Equivalent to
`Array.prototype.reduce`.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/reduce.ts#L27>

**Data First**

```ts
reduce(data, callbackfn, initialValue)
```

**Parameters**

- `data`: The items to reduce.
- `callbackfn`: A function to execute for each element in the array. Its
return value becomes the value of the accumulator parameter on the next
invocation of callbackFn. For the last invocation, the return value becomes
the return value of reduce().
- `initialValue`: A value to which accumulator is initialized the first
time the callback is called. CallbackFn starts executing with the first value
in the array as currentValue.

**Returns** `Object` — The value that results from running the "reducer" callback function
to completion over the entire array.

**Example**

```ts
reduce([1, 2, 3, 4, 5], (acc, x) => acc + x, 100); // => 115
```

**Data Last**

```ts
reduce(fn, initialValue)(array)
```

**Parameters**

- `callbackfn`: A function to execute for each element in the array. Its
return value becomes the value of the accumulator parameter on the next
invocation of callbackFn. For the last invocation, the return value becomes
the return value of reduce().
- `initialValue`: A value to which accumulator is initialized the first
time the callback is called. CallbackFn starts executing with the first value
in the array as currentValue.

**Returns** `Function` — The value that results from running the "reducer" callback function
to completion over the entire array.

**Example**

```ts
pipe(
  [1, 2, 3, 4, 5],
  reduce((acc, x) => acc + x, 100),
); // => 115
```

### reverse

Reverses array.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/reverse.ts#L27>

**Data First**

```ts
reverse(arr)
```

**Parameters**

- `array`: The array.

**Returns** `Object`

**Example**

```ts
reverse([1, 2, 3]); // [3, 2, 1]
```

**Data Last**

```ts
reverse()(array)
```

**Returns** `Function`

**Example**

```ts
reverse()([1, 2, 3]); // [3, 2, 1]
```

### sample

Returns a random subset of size `sampleSize` from `array`.

Maintains and infers most of the typing information that could be passed
along to the output. This means that when using tuples, the output will be
a tuple too, and when using literals, those literals would be preserved.

The items in the result are kept in the same order as they are in the input.
If you need to get a shuffled response you can pipe the shuffle function
after this one.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/sample.ts#L138>

**Data First**

```ts
sample(array, sampleSize)
```

**Parameters**

- `data`: The array.
- `sampleSize`: The number of elements to take.

**Returns** `Object`

**Example**

```ts
sample(['hello', 'world'], 1); // => ["hello"] // typed string[]
sample(['hello', 'world'] as const, 1); // => ["world"] // typed ["hello" | "world"]
```

**Data Last**

```ts
sample(sampleSize)(array)
```

**Parameters**

- `sampleSize`: The number of elements to take.

**Returns** `Function`

**Example**

```ts
sample(1)(['hello', 'world']); // => ["hello"] // typed string[]
sample(1)(['hello', 'world'] as const); // => ["world"] // typed ["hello" | "world"]
```

### shuffle

Shuffles the input array, returning a new array with the same elements in a random order.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/shuffle.ts#L16>

**Data First**

```ts
shuffle(array)
```

**Parameters**

- `items`: The array to shuffle.

**Returns** `Object`

**Example**

```ts
shuffle([4, 2, 7, 5]); // => [7, 5, 4, 2]
```

**Data Last**

```ts
shuffle()(array)
```

**Returns** `Function`

**Example**

```ts
pipe([4, 2, 7, 5], shuffle()); // => [7, 5, 4, 2]
```

### sort

Sorts an array. The comparator function should accept two values at a time
and return a negative number if the first value is smaller, a positive number
if it's larger, and zero if they are equal. Sorting is based on a native
[`sort`](#sort) function.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/sort.ts#L20>

**Data First**

```ts
sort(items, cmp)
```

**Parameters**

- `items`: The array to sort.
- `cmp`: The comparator function.

**Returns** `Object`

**Example**

```ts
sort([4, 2, 7, 5], (a, b) => a - b); // => [2, 4, 5, 7]
```

**Data Last**

```ts
sort(cmp)(items)
```

**Parameters**

- `cmp`: The comparator function.

**Returns** `Function`

**Example**

```ts
pipe(
  [4, 2, 7, 5],
  sort((a, b) => a - b),
); // => [2, 4, 5, 7]
```

### sortBy

Sorts `data` using the provided ordering rules. The [`sort`](#sort) is done via the
native `Array.prototype.sort` but is performed on a shallow copy of the array
to avoid mutating the original data.

There are several other functions that take order rules and **bypass** the
need to sort the array first (in *O(nlogn)* time):
[`firstBy`](#firstBy) === `first(sortBy(data, ...rules))`, O(n).
[`takeFirstBy`](#takeFirstBy) === `take(sortBy(data, ...rules), k)`, O(nlogk).
[`dropFirstBy`](#dropFirstBy) === `drop(sortBy(data, ...rules), k)`, O(nlogk).
[`nthBy`](#nthBy) === `sortBy(data, ...rules).at(k)`, O(n).
[`rankBy`](#rankBy) === `sortedIndex(sortBy(data, ...rules), item)`, O(n).
Refer to the docs for more details.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/sort-by.ts#L38>

**Data First**

```ts
sortBy(data, ...rules)
```

**Parameters**

- `array`: The input array.
- `...sortRules`: A variadic array of order rules defining the sorting
criteria. Each order rule is a projection function that extracts a comparable
value from the data. Sorting is based on these extracted values using the
native `<` and `>` operators. Earlier rules take precedence over later ones.
Use the syntax `[projection, "desc"]` for descending order.

**Returns** `Object` — A shallow copy of the input array sorted by the provided rules.

**Example**

```ts
sortBy([{ a: 1 }, { a: 3 }, { a: 7 }, { a: 2 }], prop('a')); // => [{ a: 1 }, { a: 2 }, { a: 3 }, { a: 7 }]
sortBy(
  [
    { color: 'red', weight: 2 },
    { color: 'blue', weight: 3 },
    { color: 'green', weight: 1 },
    { color: 'purple', weight: 1 },
  ],
  [prop('weight'), 'asc'],
  prop('color'),
); // => [
//   {color: 'green', weight: 1},
//   {color: 'purple', weight: 1},
//   {color: 'red', weight: 2},
//   {color: 'blue', weight: 3},
// ]
```

**Data Last**

```ts
sortBy(...rules)(data)
```

**Parameters**

- `...sortRules`: A variadic array of order rules defining the sorting
criteria. Each order rule is a projection function that extracts a comparable
value from the data. Sorting is based on these extracted values using the
native `<` and `>` operators. Earlier rules take precedence over later ones.
Use the syntax `[projection, "desc"]` for descending order.

**Returns** `Function` — A shallow copy of the input array sorted by the provided rules.

**Example**

```ts
pipe([{ a: 1 }, { a: 3 }, { a: 7 }, { a: 2 }], sortBy(prop('a'))); // => [{ a: 1 }, { a: 2 }, { a: 3 }, { a: 7 }]
```

### sortedIndex

Find the insertion position (index) of an item in an array with items sorted
in ascending order; so that `splice(sortedIndex, 0, item)` would result in
maintaining the array's sort-ness. The array can contain duplicates.
If the item already exists in the array the index would be of the *first*
occurrence of the item.

Runs in O(logN) time.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/sorted-index.ts#L24>

**Data First**

```ts
sortedIndex(data, item)
```

**Parameters**

- `data`: The (ascending) sorted array.
- `item`: The item to insert.

**Returns** `number` — Insertion index (In the range 0..array.length).

**Example**

```ts
sortedIndex(['a', 'a', 'b', 'c', 'c'], 'c'); // => 3
```

**Data Last**

```ts
sortedIndex(item)(data)
```

**Parameters**

- `item`: The item to insert.

**Returns** `Function` — Insertion index (In the range 0..array.length).

**Example**

```ts
pipe(['a', 'a', 'b', 'c', 'c'], sortedIndex('c')); // => 3
```

### sortedIndexBy

Find the insertion position (index) of an item in an array with items sorted
in ascending order using a value function; so that
`splice(sortedIndex, 0, item)` would result in maintaining the arrays sort-
ness. The array can contain duplicates.
If the item already exists in the array the index would be of the *first*
occurrence of the item.

Runs in O(logN) time.

See also:
[`findIndex`](#findIndex) - scans a possibly unsorted array in-order (linear search).
[`sortedIndex`](#sortedIndex) - like this function, but doesn't take a callbackfn.
[`sortedLastIndexBy`](#sortedLastIndexBy) - like this function, but finds the last suitable index.
[`sortedLastIndex`](#sortedLastIndex) - like [`sortedIndex`](#sortedIndex), but finds the last suitable index.
[`rankBy`](#rankBy) - scans a possibly unsorted array in-order, returning the index based on a sorting criteria.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/sorted-index-by.ts#L37>

**Data First**

```ts
sortedIndexBy(data, item, valueFunction)
```

**Parameters**

- `data`: The (ascending) sorted array.
- `item`: The item to insert.
- `valueFunction`: All comparisons would be performed on the result of
calling this function on each compared item. Preferably this function should
return a `number` or `string`. This function should be the same as the one
provided to sortBy to sort the array. The function is called exactly once on
each items that is compared against in the array, and once at the beginning
on `item`. When called on `item` the `index` argument is `undefined`.

**Returns** `number` — Insertion index (In the range 0..data.length).

**Example**

```ts
sortedIndexBy([{ age: 20 }, { age: 22 }], { age: 21 }, prop('age')); // => 1
```

### sortedIndexWith

Performs a **binary search** for the index of the item at which the predicate
stops returning `true`. This function assumes that the array is "sorted" in
regards to the predicate, meaning that running the predicate as a mapper on
it would result in an array `[...true[], ...false[]]`.
This stricter requirement from the predicate provides us 2 benefits over
[`findIndex`](#findIndex) which does a similar thing:
1. It would run at O(logN) time instead of O(N) time.
2. It always returns a value (it would return `data.length` if the
predicate returns `true` for all items).

This function is the basis for all other sortedIndex functions which search
for a specific item in a sorted array, and it could be used to perform
similar efficient searches.
[`sortedIndex`](#sortedIndex) - scans a sorted array with a binary search, find the first suitable index.
[`sortedIndexBy`](#sortedIndexBy) - like [`sortedIndex`](#sortedIndex), but assumes sorting is based on a callbackfn.
[`sortedLastIndex`](#sortedLastIndex) - scans a sorted array with a binary search, finding the last suitable index.
[`sortedLastIndexBy`](#sortedLastIndexBy) - like [`sortedLastIndex`](#sortedLastIndex), but assumes sorting is based on a callbackfn.

See also:
[`findIndex`](#findIndex) - scans a possibly unsorted array in-order (linear search).
[`rankBy`](#rankBy) - scans a possibly unsorted array in-order, returning the index based on a sorting criteria.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/sorted-index-with.ts#L38>

**Data First**

```ts
sortedIndexWith(data, predicate)
```

**Parameters**

- `data`: Array, "sorted" by `predicate`.
- `predicate`: A predicate which also defines the array's order.

**Returns** `number` — Index (In the range 0..data.length).

**Example**

```ts
sortedIndexWith(['a', 'ab', 'abc'], (item) => item.length < 2); // => 1
```

**Data Last**

```ts
sortedIndexWith(predicate)(data)
```

**Parameters**

- `predicate`: A predicate which also defines the array's order.

**Returns** `Function` — Index (In the range 0..data.length).

**Example**

```ts
pipe(
  ['a', 'ab', 'abc'],
  sortedIndexWith((item) => item.length < 2),
); // => 1
```

### sortedLastIndex

Find the insertion position (index) of an item in an array with items sorted
in ascending order; so that `splice(sortedIndex, 0, item)` would result in
maintaining the array's sort-ness. The array can contain duplicates.
If the item already exists in the array the index would be of the *last*
occurrence of the item.

Runs in O(logN) time.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/sorted-last-index.ts#L24>

**Data First**

```ts
sortedLastIndex(data, item)
```

**Parameters**

- `data`: The (ascending) sorted array.
- `item`: The item to insert.

**Returns** `number` — Insertion index (In the range 0..data.length).

**Example**

```ts
sortedLastIndex(['a', 'a', 'b', 'c', 'c'], 'c'); // => 5
```

**Data Last**

```ts
sortedLastIndex(item)(data)
```

**Parameters**

- `item`: The item to insert.

**Returns** `Function` — Insertion index (In the range 0..data.length).

**Example**

```ts
pipe(['a', 'a', 'b', 'c', 'c'], sortedLastIndex('c')); // => 5
```

### sortedLastIndexBy

Find the insertion position (index) of an item in an array with items sorted
in ascending order using a value function; so that
`splice(sortedIndex, 0, item)` would result in maintaining the arrays sort-
ness. The array can contain duplicates.
If the item already exists in the array the index would be of the *last*
occurrence of the item.

Runs in O(logN) time.

See also:
[`findIndex`](#findIndex) - scans a possibly unsorted array in-order (linear search).
[`sortedLastIndex`](#sortedLastIndex) - a simplified version of this function, without a callbackfn.
[`sortedIndexBy`](#sortedIndexBy) - like this function, but returns the first suitable index.
[`sortedIndex`](#sortedIndex) - like [`sortedLastIndex`](#sortedLastIndex) but without a callbackfn.
[`rankBy`](#rankBy) - scans a possibly unsorted array in-order, returning the index based on a sorting criteria.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/sorted-last-index-by.ts#L37>

**Data First**

```ts
sortedLastIndexBy(data, item, valueFunction)
```

**Parameters**

- `data`: The (ascending) sorted array.
- `item`: The item to insert.
- `valueFunction`: All comparisons would be performed on the result of
calling this function on each compared item. Preferably this function should
return a `number` or `string`. This function should be the same as the one
provided to sortBy to sort the array. The function is called exactly once on
each items that is compared against in the array, and once at the beginning
on `item`. When called on `item` the `index` argument is `undefined`.

**Returns** `number` — Insertion index (In the range 0..data.length).

**Example**

```ts
sortedLastIndexBy([{ age: 20 }, { age: 22 }], { age: 21 }, prop('age')); // => 1
```

**Data Last**

```ts
sortedLastIndexBy(item, valueFunction)(data)
```

**Parameters**

- `item`: The item to insert.
- `valueFunction`: All comparisons would be performed on the result of
calling this function on each compared item. Preferably this function should
return a `number` or `string`. This function should be the same as the one
provided to sortBy to sort the array. The function is called exactly once on
each items that is compared against in the array, and once at the beginning
on `item`. When called on `item` the `index` argument is `undefined`.

**Returns** `Function` — Insertion index (In the range 0..data.length).

**Example**

```ts
pipe([{ age: 20 }, { age: 22 }], sortedLastIndexBy({ age: 21 }, prop('age'))); // => 1
```

### splice

Removes elements from an array and, optionally, inserts new elements in
their place.

Related operations:
- [`drop`](#drop) - to skip past the first `n` elements.
- [`dropLast`](#dropLast) - to skip past the last `n` elements.
- [`filter`](#filter) - to shape the array by *value* rather than by *position*.
- [`swapIndices`](#swapIndices) - to swap two elements by their indices.
- [`take`](#take) - to keep only the first `n` elements.
- [`takeLast`](#takeLast) - to keep only the last `n` elements.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/splice.ts#L29>

**Data First**

```ts
splice(data, start, deleteCount)
splice(data, start, deleteCount, replacement)
```

**Parameters**

- `data`: The array to splice.
- `start`: The index from which to start removing elements.
- `deleteCount`: The number of elements to remove.
- `replacement` (optional): Elements to insert at the cutoff point.

**Returns** `Array`

**Example**

```ts
splice([1, 2, 3, 4, 5, 6, 7, 8], 2, 3); //=> [1,2,6,7,8]
splice([1, 2, 3, 4, 5, 6, 7, 8], 2, 3, [9, 10]); //=> [1,2,9,10,6,7,8]
```

**Data Last**

```ts
splice(start, deleteCount)(data)
splice(start, deleteCount, replacement)(data)
```

**Parameters**

- `start`: The index from which to start removing elements.
- `deleteCount`: The number of elements to remove.
- `replacement` (optional): Elements to insert at the cutoff point.

**Returns** `Function`

**Example**

```ts
pipe([1, 2, 3, 4, 5, 6, 7, 8], splice(2, 3)); // => [1,2,6,7,8]
pipe([1, 2, 3, 4, 5, 6, 7, 8], splice(2, 3, [9, 10])); // => [1,2,9,10,6,7,8]
```

### splitAt

Splits a given array at a given index.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/split-at.ts#L16>

**Data First**

```ts
splitAt(array, index)
```

**Parameters**

- `array`: The array to split.
- `index`: The index to split at.

**Returns** `Array`

**Example**

```ts
splitAt([1, 2, 3], 1); // => [[1], [2, 3]]
splitAt([1, 2, 3, 4, 5], -1); // => [[1, 2, 3, 4], [5]]
```

**Data Last**

```ts
splitAt(index)(array)
```

**Parameters**

- `index`: The index to split at.

**Returns** `Function`

**Example**

```ts
splitAt(1)([1, 2, 3]); // => [[1], [2, 3]]
splitAt(-1)([1, 2, 3, 4, 5]); // => [[1, 2, 3, 4], [5]]
```

### splitWhen

Splits a given array at the first index where the given predicate returns true.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/split-when.ts#L15>

**Data First**

```ts
splitWhen(array, fn)
```

**Parameters**

- `data`: The array to split.
- `predicate`: The predicate.

**Returns** `Array`

**Example**

```ts
splitWhen([1, 2, 3], (x) => x === 2); // => [[1], [2, 3]]
```

**Data Last**

```ts
splitWhen(fn)(array)
```

**Parameters**

- `predicate`: The predicate.

**Returns** `Function`

**Example**

```ts
splitWhen((x) => x === 2)([1, 2, 3]); // => [[1], [2, 3]]
```

### sumBy

Returns the sum of the elements of an array using the provided mapper.

Works for both `number` and `bigint` mappers, but not mappers that return both
types.

IMPORTANT: The result for empty arrays would be 0 (`number`) regardless of
the type of the mapper; to avoid adding this to the return type for cases
where the array is known to be non-empty you can use [`hasAtLeast`](#hasAtLeast) or
[`isEmpty`](#isEmpty) to guard against this case.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/sum-by.ts#L40>

**Data First**

```ts
sumBy(array, fn)
```

**Parameters**

- `data`: The array.
- `callbackfn`: Predicate function.

**Returns** `Object`

**Example**

```ts
sumBy([{ a: 5 }, { a: 1 }, { a: 3 }], (x) => x.a); // 9
sumBy([{ a: 5n }, { a: 1n }, { a: 3n }], (x) => x.a); // 9n
```

**Data Last**

```ts
sumBy(fn)(array)
```

**Parameters**

- `callbackfn`: Predicate function.

**Returns** `Function`

**Example**

```ts
pipe(
  [{ a: 5 }, { a: 1 }, { a: 3 }],
  sumBy((x) => x.a),
); // 9

pipe(
  [{ a: 5n }, { a: 1n }, { a: 3n }],
  sumBy((x) => x.a),
); // 9n
```

### swapIndices

Swaps the positions of two elements in an array or string at the provided indices.

Negative indices are supported and would be treated as an offset from the end of the array. The resulting type thought would be less strict than when using positive indices.

If either index is out of bounds the result would be a shallow copy of the input, as-is.

Related operations:
- [`splice`](#splice) - for more general positional edits (remove a slice, insert at an index).

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/swap-indices.ts#L115>

**Data First**

```ts
swapIndices(data, index1, index2)
```

**Parameters**

- `data`: The item to be manipulated. This can be an array, or a string.
- `index1`: The first index.
- `index2`: The second index.

**Returns** `Object` — Returns the manipulated array or string.

**Example**

```ts
swapIndices(['a', 'b', 'c'], 0, 1); // => ['b', 'a', 'c']
swapIndices(['a', 'b', 'c'], 1, -1); // => ['a', 'c', 'b']
swapIndices('abc', 0, 1); // => 'bac'
```

**Data Last**

```ts
swapIndices(index1, index2)(data)
```

**Parameters**

- `index1`: The first index.
- `index2`: The second index.

**Returns** `Function` — Returns the manipulated array or string.

**Example**

```ts
swapIndices(0, 1)(['a', 'b', 'c']); // => ['b', 'a', 'c']
swapIndices(0, -1)('abc'); // => 'cba'
```

### take (lazy)

Returns the first `n` elements of `array`.

Related operations:
- [`drop`](#drop) - to skip past the first `n` instead.
- [`splice`](#splice) - to remove or insert at an arbitrary index.
- [`takeLast`](#takeLast) - same, but from the end of the array.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/take.ts#L24>

**Data First**

```ts
take(array, n)
```

**Parameters**

- `array`: The array.
- `n`: The number of elements to take.

**Returns** `Array`

**Example**

```ts
take([1, 2, 3, 4, 3, 2, 1], 3); // => [1, 2, 3]
```

**Data Last**

```ts
take(n)(array)
```

**Parameters**

- `n`: The number of elements to take.

**Returns** `Function`

**Example**

```ts
pipe([1, 2, 3, 4, 3, 2, 1], take(3)); // => [1, 2, 3]
```

### takeFirstBy

Take the first `n` items from `data` based on the provided ordering criteria. This allows you to avoid sorting the array before taking the items. The complexity of this function is *O(Nlogn)* where `N` is the length of the array.

For the opposite operation (to drop `n` elements) see [`dropFirstBy`](#dropFirstBy).

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/take-first-by.ts#L26>

**Data First**

```ts
takeFirstBy(data, n, ...rules)
```

**Parameters**

- `data`: The input array.
- `n`: The number of items to take. If `n` is non-positive no items would be returned, if `n` is bigger then data.length a *clone* of `data` would be returned.
- `...rules`: A variadic array of order rules defining the sorting criteria. Each order rule is a projection function that extracts a comparable value from the data. Sorting is based on these extracted values using the native `<` and `>` operators. Earlier rules take precedence over later ones. Use the syntax `[projection, "desc"]` for descending order.

**Returns** `Array` — A subset of the input array.

**Example**

```ts
takeFirstBy(['aa', 'aaaa', 'a', 'aaa'], 2, (x) => x.length); // => ['aa', 'a']
```

**Data Last**

```ts
takeFirstBy(n, ...rules)(data)
```

**Parameters**

- `n`: The number of items to take. If `n` is non-positive no items would be returned, if `n` is bigger then data.length a *clone* of `data` would be returned.
- `...rules`: A variadic array of order rules defining the sorting criteria. Each order rule is a projection function that extracts a comparable value from the data. Sorting is based on these extracted values using the native `<` and `>` operators. Earlier rules take precedence over later ones. Use the syntax `[projection, "desc"]` for descending order.

**Returns** `Function` — A subset of the input array.

**Example**

```ts
pipe(
  ['aa', 'aaaa', 'a', 'aaa'],
  takeFirstBy(2, (x) => x.length),
); // => ['aa', 'a']
```

### takeLast

Takes the last `n` elements from the `array`.

Related operations:
- [`dropLast`](#dropLast) - to skip past the last `n` instead.
- [`splice`](#splice) - to remove or insert at an arbitrary index.
- [`take`](#take) - same, but from the start of the array.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/take-last.ts#L21>

**Data First**

```ts
takeLast(array, n)
```

**Parameters**

- `array`: The target array.
- `n`: The number of elements to take.

**Returns** `Array`

**Example**

```ts
takeLast([1, 2, 3, 4, 5], 2); // => [4, 5]
```

**Data Last**

```ts
takeLast(n)(array)
```

**Parameters**

- `n`: The number of elements to take.

**Returns** `Function`

**Example**

```ts
takeLast(2)([1, 2, 3, 4, 5]); // => [4, 5]
```

### takeLastWhile

Returns elements from the end of the array until the predicate returns false.
The returned elements will be in the same order as in the original array.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/take-last-while.ts#L21>

**Data First**

```ts
takeLastWhile(data, predicate)
```

**Parameters**

- `data`: The array.
- `predicate`: A function to execute for each element in the array,
starting from the end. It should return `true` to keep taking elements, and
`false` to stop. A type-predicate can also be used to narrow the result.

**Returns** `Object`

**Example**

```ts
takeLastWhile([1, 2, 10, 3, 4, 5], (x) => x < 10); // => [3, 4, 5]
```

**Data Last**

```ts
takeLastWhile(predicate)(data)
```

**Parameters**

- `predicate`: A function to execute for each element in the array,
starting from the end. It should return `true` to keep taking elements, and
`false` to stop. A type-predicate can also be used to narrow the result.

**Returns** `Function`

**Example**

```ts
pipe(
  [1, 2, 10, 3, 4, 5],
  takeLastWhile((x) => x < 10),
); // => [3, 4, 5]
```

### takeWhile

Returns elements from the array until predicate returns false.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/take-while.ts#L20>

**Data First**

```ts
takeWhile(data, predicate)
```

**Parameters**

- `data`: The array.
- `predicate`: A function to execute for each element in the array. It
should return `true` to keep taking elements, and `false` to stop. A
type-predicate can also be used to narrow the result.

**Returns** `Object`

**Example**

```ts
takeWhile([1, 2, 3, 4, 3, 2, 1], (x) => x !== 4); // => [1, 2, 3]
```

**Data Last**

```ts
takeWhile(predicate)(data)
```

**Parameters**

- `predicate`: A function to execute for each element in the array. It
should return `true` to keep taking elements, and `false` to stop. A
type-predicate can also be used to narrow the result.

**Returns** `Function`

**Example**

```ts
pipe(
  [1, 2, 3, 4, 3, 2, 1],
  takeWhile((x) => x !== 4),
); // => [1, 2, 3]
```

### times

Calls an input function `n` times, returning an array containing the results
of those function calls.

`fn` is passed one argument: The current value of `n`, which begins at `0`
and is gradually incremented to `n - 1`.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/times.ts#L51>

**Data First**

```ts
times(count, fn)
```

**Parameters**

- `count`: A value between `0` and `n - 1`. Increments after each
function call.
- `fn`: The function to invoke. Passed one argument, the current value of
`n`.

**Returns** `Object` — An array containing the return values of all calls to `fn`.

**Example**

```ts
times(5, identity()); //=> [0, 1, 2, 3, 4]
```

**Data Last**

```ts
times(fn)(count)
```

**Parameters**

- `fn`: The function to invoke. Passed one argument, the current value of
`n`.

**Returns** `Function` — An array containing the return values of all calls to `fn`.

**Example**

```ts
times(identity())(5); //=> [0, 1, 2, 3, 4]
```

### unique (lazy)

Returns a new array containing only one copy of each element in the original
list. Elements are compared by reference using Set.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/unique.ts#L20>

**Data First**

```ts
unique(array)
```

**Parameters**

- `data`: The array to filter.

**Returns** `Object`

**Example**

```ts
unique([1, 2, 2, 5, 1, 6, 7]); // => [1, 2, 5, 6, 7]
```

**Data Last**

```ts
unique()(array)
```

**Returns** `Function`

**Example**

```ts
pipe(
  [1, 2, 2, 5, 1, 6, 7], // only 4 iterations
  unique(),
  take(3),
); // => [1, 2, 5]
```

### uniqueBy (lazy)

Returns a new array containing only one copy of each element in the original
list transformed by a function. Elements are compared by reference using Set.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/unique-by.ts#L26>

**Data First**

```ts
uniqueBy(data, keyFunction)
```

**Parameters**

- `data`: The array to filter.
- `keyFunction`: Extracts a value that would be used to compare elements.

**Returns** `Object`

**Example**

```ts
uniqueBy(
  [{ n: 1 }, { n: 2 }, { n: 2 }, { n: 5 }, { n: 1 }, { n: 6 }, { n: 7 }],
  (obj) => obj.n,
); // => [{n: 1}, {n: 2}, {n: 5}, {n: 6}, {n: 7}]
```

**Data Last**

```ts
uniqueBy(keyFunction)(data)
```

**Parameters**

- `keyFunction`: Extracts a value that would be used to compare elements.

**Returns** `Function`

**Example**

```ts
pipe(
  [{ n: 1 }, { n: 2 }, { n: 2 }, { n: 5 }, { n: 1 }, { n: 6 }, { n: 7 }], // only 4 iterations
  uniqueBy((obj) => obj.n),
  take(3),
); // => [{n: 1}, {n: 2}, {n: 5}]
```

### uniqueWith (lazy)

Returns a new array containing only one copy of each element in the original
list. Elements are compared by custom comparator isEquals.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/unique-with.ts#L27>

**Data First**

```ts
uniqueWith(array, isEquals)
```

**Parameters**

- `data`: The array to filter.
- `isEquals`: The comparator.

**Returns** `Object`

**Example**

```ts
uniqueWith(
  [{ a: 1 }, { a: 2 }, { a: 2 }, { a: 5 }, { a: 1 }, { a: 6 }, { a: 7 }],
  equals,
); // => [{a: 1}, {a: 2}, {a: 5}, {a: 6}, {a: 7}]
```

**Data Last**

```ts
uniqueWith(isEquals)(array)
```

**Parameters**

- `isEquals`: The comparator.

**Returns** `Function`

**Example**

```ts
uniqueWith(equals)([
  { a: 1 },
  { a: 2 },
  { a: 2 },
  { a: 5 },
  { a: 1 },
  { a: 6 },
  { a: 7 },
]); // => [{a: 1}, {a: 2}, {a: 5}, {a: 6}, {a: 7}]
pipe(
  [{ a: 1 }, { a: 2 }, { a: 2 }, { a: 5 }, { a: 1 }, { a: 6 }, { a: 7 }], // only 4 iterations
  uniqueWith(equals),
  take(3),
); // => [{a: 1}, {a: 2}, {a: 5}]
```

### zip (lazy)

Creates a new list from two supplied lists by pairing up equally-positioned
items. The length of the returned list will match the shortest of the two
inputs.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/zip.ts#L46>

**Data First**

```ts
zip(first, second)
```

**Parameters**

- `first`: The first input list.
- `second`: The second input list.

**Returns** `Object`

**Example**

```ts
zip([1, 2], ['a', 'b']); // => [[1, 'a'], [2, 'b']]
```

**Data Last**

```ts
zip(second)(first)
```

**Parameters**

- `second`: The second input list.

**Returns** `Function`

**Example**

```ts
zip(['a', 'b'])([1, 2]); // => [[1, 'a'], [2, 'b']]
```

### zipWith (lazy)

Creates a new list from two supplied lists by calling the supplied function
with the same-positioned element from each list.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/zip-with.ts#L44>

```ts
zipWith(fn)(first, second)
```

**Parameters**

- `fn`: The function applied to each position of the list.

**Returns** `Function`

**Example**

```ts
zipWith((a: string, b: string) => a + b)(['1', '2', '3'], ['a', 'b', 'c']); // => ['1a', '2b', '3c']
```

**Data First**

```ts
zipWith(first, second, fn)
```

**Parameters**

- `first`: The first input list.
- `second`: The second input list.
- `fn`: The function applied to each position of the list.

**Returns** `Array`

**Example**

```ts
zipWith(['1', '2', '3'], ['a', 'b', 'c'], (a, b) => a + b); // => ['1a', '2b', '3c']
```

**Data Last**

```ts
zipWith(second, fn)(first)
```

**Parameters**

- `second`: The second input list.
- `fn`: The function applied to each position of the list.

**Returns** `Function`

**Example**

```ts
pipe(
  ['1', '2', '3'],
  zipWith(['a', 'b', 'c'], (a, b) => a + b),
); // => ['1a', '2b', '3c']
```

## Function

### conditional

Executes a transformer function based on the first matching predicate,
functioning like a series of `if...else if...` statements. It sequentially
evaluates each case and, upon finding a truthy predicate, runs the
corresponding transformer, and returns, ignoring any further cases, even if
they would match.

NOTE*: Some type-predicates may fail to narrow the param type of their
transformer; in such cases wrap your type-predicate in an anonymous arrow
function: e.g., instead of
`conditional(..., [myTypePredicate, myTransformer], ...)`, use
`conditional(..., [($) => myTypePredicate($), myTransformer], ...)`.

To add a a default, catch-all, case you can provide a single callback
function (instead of a 2-tuple) as the last case. This is equivalent to
adding a case with a trivial always-true predicate as it's condition (see
example).

For simpler cases you should also consider using [`when`](#when) instead.

Due to TypeScript's inability to infer the result of negating a type-
predicate we can't refine the types used in subsequent cases based on
previous conditions. Using a `switch (true)` statement or ternary operators
is recommended for more precise type control when such type narrowing is
needed.

!IMPORTANT! - Unlike similar implementations in Lodash and Ramda, this
implementation **doesn't** implicitly return `undefined` as a fallback when
when none of the cases match; and instead **throws** an exception in those
cases! You have to explicitly provide a default case, and can use
`constant(undefined)` as your last case to replicate that behavior.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/conditional.ts#L89>

**Data First**

```ts
conditional(data, ...cases)
```

**Parameters**

- `data`: The input data to be evaluated against the provided cases.
- `case0`
- `fallback` (optional)

**Returns** `Object` — The output of the matched transformer. If no cases match, an
exception is thrown. The return type is a union of the return types of all
provided transformers.

**Example**

```ts
const nameOrId = 3 as string | number | boolean;

conditional(
  nameOrId,
  [isString, (name) => `Hello ${name}`],
  [isNumber, (id) => `Hello ID: ${id}`],
); //=> 'Hello ID: 3' (typed as `string`), can throw!.

conditional(
  nameOrId,
  [isString, (name) => `Hello ${name}`],
  [isNumber, (id) => `Hello ID: ${id}`],
  constant(undefined),
); //=> 'Hello ID: 3' (typed as `string | undefined`), won't throw.

conditional(
  nameOrId,
  [isString, (name) => `Hello ${name}`],
  [isNumber, (id) => `Hello ID: ${id}`],
  (something) => `Hello something (${JSON.stringify(something)})`,
); //=> 'Hello ID: 3' (typed as `string`), won't throw.
```

**Data Last**

```ts
conditional(...cases)(data)
```

**Parameters**

- `case0`
- `fallback` (optional)

**Returns** `Function` — The output of the matched transformer. If no cases match, an
exception is thrown. The return type is a union of the return types of all
provided transformers.

**Example**

```ts
const nameOrId = 3 as string | number | boolean;

pipe(
  nameOrId,
  conditional(
    [isString, (name) => `Hello ${name}`],
    [isNumber, (id) => `Hello ID: ${id}`],
  ),
); //=> 'Hello ID: 3' (typed as `string`), can throw!.

pipe(
  nameOrId,
  conditional(
    [isString, (name) => `Hello ${name}`],
    [isNumber, (id) => `Hello ID: ${id}`],
    constant(undefined),
  ),
); //=> 'Hello ID: 3' (typed as `string | undefined`), won't throw.

pipe(
  nameOrId,
  conditional(
    [isString, (name) => `Hello ${name}`],
    [isNumber, (id) => `Hello ID: ${id}`],
    (something) => `Hello something (${JSON.stringify(something)})`,
  ),
); //=> 'Hello ID: 3' (typed as `string`), won't throw.
```

### constant

A function that takes any arguments and returns the provided `value` on every
invocation. This is useful to provide trivial implementations for APIs or in
combination with a ternary or other conditional execution to allow to short-
circuit more complex implementations for a specific case.

Notice that this is a dataLast impl where the function needs to be invoked
to get the "do nothing" function.

See also:
[`doNothing`](#doNothing) - A function that doesn't return anything.
[`identity`](#identity) - A function that returns the first argument it receives.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/constant.ts#L28>

**Data Last**

```ts
constant(value)
```

**Parameters**

- `value`: The constant value that would be returned on every invocation.
The value is not copied/cloned on every invocation so care should be taken
with mutable objects (like arrays, objects, Maps, etc...).

**Returns** `Function`

**Example**

```ts
map([1, 2, 3], constant('a')); // => ['a', 'a', 'a']
map([1, 2, 3], isDemoMode ? add(1) : constant(0)); // => [2, 3, 4] or [0, 0, 0]
```

### curry

Wraps a `dataFirst` implementation and dynamically curries it at runtime
based on the number of arguments it was called with.

When `args` has at least `dataFirst.length` items (`Function.length` counts
the parameters before the first defaulted or rest one), `dataFirst` is
called with all of them, extra ones included. Otherwise [`curry`](#curry) returns a
function that takes the data and calls `dataFirst(data, ...args)`.

The return type is not dynamically routed via the same runtime logic, and
therefore is a union of both data-first and data-last return types. The
return type also ignores any generic type parameters of `dataFirst`, and in
most cases would end up widening the return type to `unknown`. See the
examples below for a structured template for coupling the return types to
specific overloaded signatures. Almost all Perkakas utilities are built using
[`curry`](#curry) via this template.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/curry.ts#L55>

```ts
curry(dataFirst, args)
```

**Parameters**

- `dataFirst`: The function to curry.
- `args`: The arguments.

**Returns** `Object`

**Example**

```ts
// data-first
function findIndex<T>(
  data: readonly T[],
  predicate: (item: T) => boolean,
): number;

// data-last
function findIndex<T>(
  predicate: (item: T) => boolean,
): (data: readonly T[]) => number;

function findIndex(...args: unknown[]) {
  return curry(findIndexImplementation, args);
}

function findIndexImplementation(data, predicate): number {
  for (let i = 0; i < array.length; i++) {
    if (predicate(array[i])) {
      return i;
    }
  }
  return -1;
}
```

### debounce (deprecated)

Wraps `func` with a debouncer object that "debounces" (delays) invocations of the function during a defined cool-down period (`waitMs`). It can be configured to invoke the function either at the start of the cool-down period, the end of it, or at both ends (`timing`).
It can also be configured to allow invocations during the cool-down period (`maxWaitMs`).
It stores the latest call's arguments so they could be used at the end of the cool-down period when invoking `func` (if configured to invoke the function at the end of the cool-down period).
It stores the value returned by `func` whenever its invoked. This value is returned on every call, and is accessible via the `cachedValue` property of the debouncer. Its important to note that the value might be different from the value that would be returned from running `func` with the current arguments as it is a cached value from a previous invocation.
**Important**: The cool-down period defines the minimum between two invocations, and not the maximum. The period will be **extended** each time a call is made until a full cool-down period has elapsed without any additional calls.

! **DEPRECATED**: This implementation of debounce is known to have issues and might not behave as expected. It should be replaced with the [`funnel`](#funnel) utility instead. The test file [funnel.perkakas-debounce.spec.ts](https://github.com/vinicunca/perkakas/blob/main/src/funnel.perkakas-debounce.spec.ts) offers a drop-in replacement implemented via [`funnel`](#funnel): copy everything between its REFERENCE START and REFERENCE END markers into your project!

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/debounce.ts#L102>

**Data First**

```ts
debounce(func, options)
```

**Parameters**

- `func`: The function to debounce, the returned `call` function will have
the exact same signature.
- `options`: An object allowing further customization of the debouncer:
- `timing?: 'leading' | 'trailing' |'both'`. The default is `'trailing'`.
  `leading` would result in the function being invoked at the start of the
  cool-down period; `trailing` would result in the function being invoked at
  the end of the cool-down period (using the args from the last call to the
  debouncer). When `both` is selected the `trailing` invocation would only
  take place if there were more than one call to the debouncer during the
  cool-down period. **DEFAULT: 'trailing'**
- `waitMs?: number`. The length of the cool-down period in milliseconds. The
  debouncer would wait until this amount of time has passed without **any**
  additional calls to the debouncer before triggering the end-of-cool-down-
  period event. When this happens, the function would be invoked (if `timing`
  isn't `'leading'`) and the debouncer state would be reset. **DEFAULT: 0**
- `maxWaitMs?: number`. The length of time since a debounced call (a call
  that the debouncer prevented from being invoked) was made until it would be
  invoked. Because the debouncer can be continually triggered and thus never
  reach the end of the cool-down period, this allows the function to still
  be invoked occasionally. IMPORTANT: This param is ignored when `timing` is
  `'leading'`.

**Returns** `Object` — A debouncer object. The main function is `call`. In addition to it
the debouncer comes with the following additional functions and properties:
- `cancel` method to cancel delayed `func` invocations
- `flush` method to end the cool-down period immediately.
- `cachedValue` the latest return value of an invocation (if one occurred).
- `isPending` flag to check if there is an inflight cool-down window.

**Example**

```ts
const debouncer = debounce(identity(), { timing: 'trailing', waitMs: 1000 });
const result1 = debouncer.call(1); // => undefined
const result2 = debouncer.call(2); // => undefined
// after 1 second
const result3 = debouncer.call(3); // => 2
// after 1 second
debouncer.cachedValue; // => 3
```

### doNothing

A function that takes any arguments and does nothing with them. This is
useful as a placeholder for any function or API that requires a **void**
function (a function that doesn't return a value). This could also be used in
combination with a ternary or other conditional execution to allow disabling
a function call for a specific case.

Notice that this is a dataLast impl where the function needs to be invoked
to get the "do nothing" function.

See also:
[`constant`](#constant) - A function that ignores it's arguments and returns the same value on every invocation.
[`identity`](#identity) - A function that returns the first argument it receives.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/do-nothing.ts#L23>

**Data Last**

```ts
doNothing()
```

**Returns** `Function`

**Example**

```ts
myApi({ onSuccess: handleSuccess, onError: doNothing() });
myApi({ onSuccess: isDemoMode ? doNothing() : handleSuccess });
```

### funnel

Creates a funnel that controls the timing and execution of `callback`. Its
main purpose is to manage multiple consecutive (usually fast-paced) calls,
reshaping them according to a defined batching strategy and timing policy.
This is useful when handling uncontrolled call rates, such as DOM events or
network traffic. It can implement strategies like debouncing, throttling,
batching, and more.

An optional `reducer` function can be provided to allow passing data to the
callback via calls to `call` (otherwise the signature of `call` takes no
arguments).

Typing is inferred from `callback`s param, and from the rest params that
the optional `reducer` function accepts. Use **explicit** types for these
to ensure that everything _else_ is well-typed.

Notice that this function constructs a funnel **object**, and does **not**
execute anything when called. The returned object should be used to execute
the funnel via the its `call` method.

The type of the funnel object is not exported; when you need to reference
it explicitly (e.g., a class property holding a funnel) use
`ReturnType<typeof funnel<[]>>`, replacing `[]` with the `reducer`'s rest
params when one is used (e.g., `ReturnType<typeof funnel<[string]>>`).

- Debouncing: use `minQuietPeriodMs` and any `triggerAt`. Copy-paste
reference implementations are available for Perkakas's deprecated [`debounce`](#debounce)
function in [`funnel.perkakas-debounce.spec.ts`](https://github.com/vinicunca/perkakas/blob/main/src/funnel.perkakas-debounce.spec.ts),
and for the Lodash [`debounce`](#debounce) function in [`funnel.lodash-debounce.spec.ts`](https://github.com/vinicunca/perkakas/blob/main/src/funnel.lodash-debounce.spec.ts)
and [`funnel.lodash-debounce-with-cached-value.spec.ts`](https://github.com/vinicunca/perkakas/blob/main/src/funnel.lodash-debounce-with-cached-value.spec.ts).
- Throttling: use `minGapMs` and `triggerAt: "start"` or `"both"`.
Copy-paste reference implementations for the Lodash `throttle` function
(which maps onto the burst options `minQuietPeriodMs` and
`maxBurstDurationMs` instead of `minGapMs`) are available in [`funnel.lodash-throttle.spec.ts`](https://github.com/vinicunca/perkakas/blob/main/src/funnel.lodash-throttle.spec.ts)
and [`funnel.lodash-throttle-with-cached-value.spec.ts`](https://github.com/vinicunca/perkakas/blob/main/src/funnel.lodash-throttle-with-cached-value.spec.ts).
- Batching: a copy-paste reference implementation is available in [`funnel.reference-batch.spec.ts`](https://github.com/vinicunca/perkakas/blob/main/src/funnel.reference-batch.spec.ts).

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/funnel.ts#L175>

```ts
funnel(callback, options)
```

**Parameters**

- `callback`: The main function that would be invoked periodically based
on `options`. The function would take the latest result of the `reducer`; if
no calls where made since the last time it was invoked it will not be
invoked. (If a return value is needed, it should be passed via a reference or
via closure to the outer scope of the funnel).
- `options`: An object that defines when `execute` should be invoked,
relative to the calls of `call`. An empty/missing options object is
equivalent to setting `minQuietPeriodMs` to `0`.

**Returns** `Object` — A funnel with a `call` function that is used to trigger invocations.
In addition to it the funnel also comes with the following functions and
properties:
- `cancel` - Resets the funnel to it's initial state, discarding the current
`reducer` result without calling `execute` on it.
- `flush` - Triggers an invocation even if there are active timeouts, and
then resets the funnel to it's initial state.
- `isIdle` - Checks if there are any active timeouts.

**Example**

```ts
const debouncer = funnel(
  () => {
    console.log('Callback executed!');
  },
  { minQuietPeriodMs: 100 },
);
debouncer.call();
debouncer.call();

const throttle = funnel(
  () => {
    console.log('Callback executed!');
  },
  { minGapMs: 100, triggerAt: 'start' },
);
throttle.call();
throttle.call();
```

### identity

A function that returns the first argument passed to it.

Notice that this is a dataLast impl where the function needs to be invoked
to get the "do nothing" function.

See also:
[`doNothing`](#doNothing) - A function that doesn't return anything.
[`constant`](#constant) - A function that ignores the input arguments and returns the same value on every invocation.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/identity.ts#L23>

```ts
identity()
```

**Returns** `Object`

**Example**

```ts
map([1, 2, 3], identity()); // => [1,2,3]
```

### once

Creates a function that is restricted to invoking `func` once. Repeat calls to the function return the value of the first invocation.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/once.ts#L13>

```ts
once(fn)
```

**Parameters**

- `fn`: The function to wrap.

**Returns** `Function`

**Example**

```ts
const initialize = once(createApplication);
initialize();
initialize();
// => `createApplication` is invoked once
```

### partialBind

Creates a function that calls `func` with `partial` put before the arguments
it receives.

Can be thought of as "freezing" some portion of a function's arguments,
resulting in a new function with a simplified signature.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/partial-bind.ts#L59>

**Data First**

```ts
partialBind(func, ...partial)
```

**Parameters**

- `func`: The function to wrap.
- `...partial`: The arguments to put before.

**Returns** `Function` — A partially bound function.

**Example**

```ts
const fn = (x: number, y: number, z: number) => x * 100 + y * 10 + z;
const partialFn = partialBind(fn, 1, 2);
partialFn(3); //=> 123

const logWithPrefix = partialBind(console.log, '[prefix]');
logWithPrefix('hello'); //=> "[prefix] hello"
```

### partialLastBind

Creates a function that calls `func` with `partial` put after the arguments
it receives. Note that this doesn't support functions with both optional
and rest parameters.

Can be thought of as "freezing" some portion of a function's arguments,
resulting in a new function with a simplified signature.

Useful for converting a data-first function to a data-last one.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/partial-last-bind.ts#L68>

**Data First**

```ts
partialLastBind(func, ...partial)
```

**Parameters**

- `func`: The function to wrap.
- `...partial`: The arguments to put after.

**Returns** `Function` — A partially bound function.

**Example**

```ts
const fn = (x: number, y: number, z: number) => x * 100 + y * 10 + z;
const partialFn = partialLastBind(fn, 2, 3);
partialFn(1); //=> 123

const parseBinary = partialLastBind(parseInt, '2');
parseBinary('101'); //=> 5

pipe(
  { a: 1 },
  // instead of (arg) => JSON.stringify(arg, null, 2)
  partialLastBind(JSON.stringify, null, 2),
); //=> '{\n  "a": 1\n}'
```

### pipe

Performs left-to-right function composition, passing data through functions
in sequence. Each function receives the output of the previous function,
creating a readable top-to-bottom data flow that matches how the
transformation is executed. This enables converting deeply nested function
calls into clear, sequential steps without temporary variables.

When consecutive functions with a `lazy` tag (e.g., [`map`](#map), [`filter`](#filter), [`take`](#take),
[`drop`](#drop), [`forEach`](#forEach), etc...) are used together, they process data item-by-item
rather than creating intermediate arrays. This enables early termination
when only partial results are needed, improving performance for large
datasets and expensive operations.

Functions are only evaluated lazily when their data-last form is used
directly in the pipe. To disable lazy evaluation, use data-first calls via
arrow functions: `($) => map($, callback)` instead of `map(callback)`.

Any function can be used in pipes, not just Perkakas utilities. For creating
custom functions that support both data-first and data-last calls, see the
[`curry`](#curry) utility.

A "headless" variant [`piped`](#piped) is available for creating reusable pipe
functions without initial data.

IMPORTANT: During lazy evaluation, callbacks using the third parameter (the
input array) receive only items processed up to that point, not the complete
array.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/pipe.ts#L125>

**Data First**

```ts
pipe(data, ...functions)
```

**Parameters**

- `data`: The input data.

**Returns** `Object`

**Example**

```ts
pipe([1, 2, 3], map(multiply(3))); //=> [3, 6, 9]

// = Early termination with lazy evaluation =
pipe(
  hugeArray,
  map(expensiveComputation),
  filter(complexPredicate),
  // Only processes items until 2 results are found, then stops.
  // Most of hugeArray never gets processed.
  take(2),
);

// = Custom logic within a pipe =
pipe(
  input,
  toLowerCase(),
  normalize,
  ($) => validate($, CONFIG),
  split(','),
  unique(),
);

// = Migrating nested transformations to pipes =
// Nested
const result = prop(
  mapValues(groupByProp(users, 'department'), length()),
  'engineering',
);

// Piped
const result = pipe(
  users,
  groupByProp('department'),
  mapValues(length()),
  prop('engineering'),
);

// = Using the 3rd param of a callback =
// The following would print out `data` in its entirety for each value
// of `data`.
forEach([1, 2, 3, 4], (_item, _index, data) => {
  console.log(data);
}); //=> "[1, 2, 3, 4]" logged 4 times

// But with `pipe` data would only contain the items up to the current
// index.
pipe(
  [1, 2, 3, 4],
  forEach((_item, _index, data) => {
    console.log(data);
  }),
); //=> "[1]", "[1, 2]", "[1, 2, 3]", "[1, 2, 3, 4]"
```

### piped

Data-last version of [`pipe`](#pipe). See [`pipe`](#pipe) documentation for full details.

Use [`piped`](#piped) when you need to pass a transformation as a callback to
functions like [`map`](#map) and [`filter`](#filter), where the data type can be inferred
from the call site.

IMPORTANT: [`piped`](#piped) does not work as a "function factory" in order to create
standalone utility functions; because TypeScript cannot infer the input data
type (without requiring to explicitly define all type params for all
functions in the pipe). We recommend defining the function explicitly, and
then use [`pipe`](#pipe) in its implementation.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/piped.ts#L26>

**Data Last**

```ts
piped(...functions)(data)
```

**Returns** `Function`

**Example**

```ts
map([{ a: 1 }, { a: 2 }, { a: 3 }], piped(prop('a'), add(1))); //=> [2, 3, 4]
```

### sleep

Delay execution for a given number of milliseconds.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/sleep.ts#L12>

```ts
sleep(timeout)
```

**Parameters**

- `timeout`: the number of milliseconds to wait

**Returns** `Promise`

**Example**

```ts
sleep(1000); // => Promise<void>
```

### when

Conditionally run a function based on a predicate, returning its result (similar to
the [`?:` (ternary) operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_operator).)
If the optional `onFalse` function is not provided, the data will be passed
through in those cases.

Supports type predicates to refine the types for both branches and the return
value.

Additional arguments are passed to all functions. In data-first calls, they
are taken as variadic arguments; but in data-last calls, they are when the
curried function itself is called.

For more complex cases check out [`conditional`](#conditional).

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/when.ts#L36>

**Data First**

```ts
when(data, predicate, onTrue, ...extraArgs)
when(data, predicate, { onTrue, onFalse }, ...extraArgs)
```

**Parameters**

- `data`: The data to be passed to all functions, as the first param.
- `predicate`: Decides if the `onTrue` mapper should run or not. If it's
a type predicate it also narrows types for the mappers and the return value.
- `onTrue`: The function that would run when the predicate returns
`true`.
- `...extraArgs`: Additional arguments. These would be passed as is to the
`predicate`, `onTrue`, and `onFalse` functions.

**Returns** `Object`

**Example**

```ts
when(data, isNullish, constant(42));
when(data, (x) => x > 3, { onTrue: add(1), onFalse: multiply(2) });
when(data, isString, (x, radix) => parseInt(x, radix), 10);
```

**Data Last**

```ts
when(predicate, onTrue)(data, ...extraArgs)
when(predicate, { onTrue, onFalse })(data, ...extraArgs)
```

**Parameters**

- `predicate`: Decides if the `onTrue` mapper should run or not. If it's
a type predicate it also narrows types for the mappers and the return value.
- `onTrue`: Function to run when the predicate returns `true`.

**Returns** `Function`

**Example**

```ts
pipe(data, when(isNullish, constant(42)));
pipe(
  data,
  when((x) => x > 3, { onTrue: add(1), onFalse: multiply(2) }),
);
map(
  data,
  when(isNullish, (x, index) => x + index),
);
```

## Guard

### hasProp

Checks if `data` has a prop `key`.

Uses [`Object.hasOwn`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn)
which only checks own properties, skipping properties inherited through the
prototype chain.

- Use [`prop`](#prop) to read the value.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/has-prop.ts#L43>

**Data First**

```ts
hasProp(data, key)
```

**Parameters**

- `data`: The object to test.
- `key`: The key to look up.

**Returns** `boolean`

**Example**

```ts
hasProp({ a: 1 }, 'a'); //=> true
```

**Data Last**

```ts
hasProp(key)(data)
```

**Parameters**

- `key`: The key to look up.

**Returns** `Function`

**Example**

```ts
pipe({ a: 1 }, hasProp('a')); //=> true
filter([] as { a?: number }[], hasProp('a')); //=> typed as { a: number }[]
```

### hasSubObject

Checks if `subObject` is a sub-object of `object`, which means for every
property and value in `subObject`, there's the same property in `object`
with an equal value. Equality is checked with [`isDeepEqual`](#isDeepEqual).

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/has-sub-object.ts#L79>

**Data First**

```ts
hasSubObject(data, subObject)
```

**Parameters**

- `data`: The object to test.
- `subObject`: The sub-object to test against.

**Returns** `boolean`

**Example**

```ts
hasSubObject({ a: 1, b: 2, c: 3 }, { a: 1, c: 3 }); //=> true
hasSubObject({ a: 1, b: 2, c: 3 }, { b: 4 }); //=> false
hasSubObject({ a: 1, b: 2, c: 3 }, {}); //=> true
```

**Data Last**

```ts
hasSubObject(subObject)(data)
```

**Parameters**

- `subObject`: The sub-object to test against.

**Returns** `Function`

**Example**

```ts
hasSubObject({ a: 1, c: 3 })({ a: 1, b: 2, c: 3 }); //=> true
hasSubObject({ b: 4 })({ a: 1, b: 2, c: 3 }); //=> false
hasSubObject({})({ a: 1, b: 2, c: 3 }); //=> true
```

### isArray

A function that checks if the passed parameter is an Array and narrows its type accordingly.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/is-array.ts#L16>

```ts
isArray(data)
```

**Parameters**

- `data`: The variable to check.

**Returns** `boolean` — True if the passed input is an Array, false otherwise.

**Example**

```ts
isArray([5]); //=> true
isArray([]); //=> true
isArray('somethingElse'); //=> false
```

### isBigInt

A function that checks if the passed parameter is a bigint and narrows its
type accordingly.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/is-big-int.ts#L17>

```ts
isBigInt(data)
```

**Parameters**

- `data`: The variable to check.

**Returns** `boolean` — True if the passed input is a number, false otherwise.

**Example**

```ts
isBigInt(1n); // => true
isBigInt(1); // => false
isBigInt('notANumber'); // => false
```

### isBoolean

A function that checks if the passed parameter is a boolean and narrows its type accordingly.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/is-boolean.ts#L16>

```ts
isBoolean(data)
```

**Parameters**

- `data`: The variable to check.

**Returns** `boolean` — True if the passed input is a boolean, false otherwise.

**Example**

```ts
isBoolean(true); //=> true
isBoolean(false); //=> true
isBoolean('somethingElse'); //=> false
```

### isDate

A function that checks if the passed parameter is a Date and narrows its type accordingly.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/is-date.ts#L13>

```ts
isDate(data)
```

**Parameters**

- `data`: The variable to check.

**Returns** `boolean` — True if the passed input is a Date, false otherwise.

**Example**

```ts
isDate(new Date()); //=> true
isDate('somethingElse'); //=> false
```

### isDeepEqual

Performs a *deep structural* comparison between two values to determine if
they are equivalent. For primitive values this is equivalent to `===`, for
arrays the check would be performed on every item recursively, in order, and
for objects all props will be compared recursively.

The built-in Date and RegExp are special-cased and will be compared by their
values. Objects with a `null` prototype are comparable to plain objects by
their enumerable properties.

!IMPORTANT: TypedArrays and symbol properties of objects are not supported
right now and might result in unexpected behavior.

The result would be narrowed to the second value so that the function can be
used as a type guard.

See:
- [`isStrictEqual`](#isStrictEqual) if you don't need a deep comparison and just want to
check for simple (`===`, `Object.is`) equality.
- [`isShallowEqual`](#isShallowEqual) if you need to compare arrays and objects "by-value" but
don't want to recurse into their values.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/is-deep-equal.ts#L37>

**Data First**

```ts
isDeepEqual(data, other)
```

**Parameters**

- `data`: The first value to compare.
- `other`: The second value to compare.

**Returns** `boolean`

**Example**

```ts
isDeepEqual(1, 1); //=> true
isDeepEqual(1, '1'); //=> false
isDeepEqual([1, 2, 3], [1, 2, 3]); //=> true
```

**Data Last**

```ts
isDeepEqual(other)(data)
```

**Parameters**

- `other`: The second value to compare.

**Returns** `Function`

**Example**

```ts
pipe(1, isDeepEqual(1)); //=> true
pipe(1, isDeepEqual('1')); //=> false
pipe([1, 2, 3], isDeepEqual([1, 2, 3])); //=> true
```

### isDefined

A function that checks if the passed parameter is defined (`!== undefined`)
and narrows its type accordingly.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/is-defined.ts#L15>

```ts
isDefined(data)
```

**Parameters**

- `data`: The variable to check.

**Returns** `boolean` — True if the passed input is defined, false otherwise.

**Example**

```ts
isDefined('string'); //=> true
isDefined(null); //=> true
isDefined(undefined); //=> false
```

### isEmpty

A function that checks if the passed parameter is empty.

This function has *limited* utility at the type level because **negating** it
does not yield a useful type in most cases because of TypeScript
limitations. Additionally, utilities which accept a narrower input type
provide better type-safety on their inputs. In most cases, you should use
one of the following functions instead:
[`isEmptyish`](#isEmptyish) - supports a wider range of cases, accepts any input including nullish values, and does a better job at narrowing the result.
[`hasAtLeast`](#hasAtLeast) - when the input is just an array/tuple.
[`isStrictEqual`](#isStrictEqual) - when you just need to check for a specific literal value.
[`isNullish`](#isNullish) - when you just care about `null` and `undefined`.
[`isTruthy`](#isTruthy) - when you need to also filter `number` and `boolean`.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/is-empty.ts#L32>

```ts
isEmpty(data)
```

**Parameters**

- `data`: The variable to check.

**Returns** `boolean`

**Example**

```ts
isEmpty(''); //=> true
isEmpty([]); //=> true
isEmpty({}); //=> true

isEmpty('test'); //=> false
isEmpty([1, 2, 3]); //=> false
isEmpty({ a: 'hello' }); //=> false

isEmpty(undefined); // Deprecated: use `isEmptyish`
```

### isEmptyish

A function that checks if the input is empty. Empty is defined as anything
exposing a numerical [`length`](#length), or `size` property that is equal to `0`. This
definition covers strings, arrays, Maps, Sets, plain objects, and custom
classes. Additionally, `null` and `undefined` are also considered empty.

`number`, `bigint`, `boolean`, `symbol`, and `function` will always return
`false`. `RegExp`, `Date`, and weak collections will always return `true`.
Classes and Errors are treated as plain objects: if they expose any public
property they would be considered non-empty, unless they expose a numerical
[`length`](#length) or `size` property, which defines their emptiness regardless of
other properties.

This function has *limited* utility at the type level because **negating** it
does not yield a useful type in most cases because of TypeScript
limitations. Additionally, utilities which accept a narrower input type
provide better type-safety on their inputs. In most cases, you should use
one of the following functions instead:
[`isEmpty`](#isEmpty) - provides better type-safety on inputs by accepting a narrower set of cases.
[`hasAtLeast`](#hasAtLeast) - when the input is just an array/tuple.
[`isStrictEqual`](#isStrictEqual) - when you just need to check for a specific literal value.
[`isNullish`](#isNullish) - when you just care about `null` and `undefined`.
[`isTruthy`](#isTruthy) - when you need to also filter `number` and `boolean`.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/is-emptyish.ts#L182>

```ts
isEmptyish(data)
```

**Parameters**

- `data`: The variable to check.

**Returns** `boolean`

**Example**

```ts
isEmptyish(undefined); //=> true
isEmptyish(null); //=> true
isEmptyish(''); //=> true
isEmptyish([]); //=> true
isEmptyish({}); //=> true
isEmptyish(new Map()); //=> true
isEmptyish(new Set()); //=> true
isEmptyish({ a: 'hello', size: 0 }); //=> true
isEmptyish(/abc/); //=> true
isEmptyish(new Date()); //=> true
isEmptyish(new WeakMap()); //=> true

isEmptyish('test'); //=> false
isEmptyish([1, 2, 3]); //=> false
isEmptyish({ a: 'hello' }); //=> false
isEmptyish({ length: 1 }); //=> false
isEmptyish(0); //=> false
isEmptyish(true); //=> false
isEmptyish(() => {}); //=> false
```

### isError

A function that checks if the passed parameter is an Error and narrows its type accordingly.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/is-error.ts#L17>

```ts
isError(data)
```

**Parameters**

- `data`: The variable to check.

**Returns** `boolean` — True if the passed input is an Error, false otherwise.

**Example**

```ts
isError(new Error('message')); //=> true
isError('somethingElse'); //=> false
```

### isFunction

A function that checks if the passed parameter is a Function and narrows its type accordingly.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/is-function.ts#L16>

```ts
isFunction(data)
```

**Parameters**

- `data`: The variable to check.

**Returns** `boolean` — True if the passed input is a Function, false otherwise.

**Example**

```ts
isFunction(() => {}); //=> true
isFunction('somethingElse'); //=> false
```

### isIncludedIn

Checks if the item is included in the container. This is a wrapper around
`Array.prototype.includes` and `Set.prototype.has` and thus relies on the
same equality checks that those functions do (which is reference equality,
e.g. `===`). In some cases the input's type is also narrowed to the
container's item types.

Notice that unlike most functions, this function takes a generic item as it's
data and **an array** as it's parameter.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/is-included-in.ts#L95>

**Data First**

```ts
isIncludedIn(data, container)
```

**Parameters**

- `data`: The item that is checked.
- `container`: The items that are checked against.

**Returns** `boolean` — `true` if the item is in the container, or `false` otherwise. In
cases the type of `data` is also narrowed down.

**Example**

```ts
isIncludedIn(2, [1, 2, 3]); // => true
isIncludedIn(4, [1, 2, 3]); // => false

const data = 'cat' as 'cat' | 'dog' | 'mouse';
isIncludedIn(data, ['cat', 'dog'] as const); // true (typed "cat" | "dog");
```

**Data Last**

```ts
isIncludedIn(container)(data)
```

**Parameters**

- `container`: The items that are checked against.

**Returns** `Function` — `true` if the item is in the container, or `false` otherwise. In
cases the type of `data` is also narrowed down.

**Example**

```ts
pipe(2, isIncludedIn([1, 2, 3])); // => true
pipe(4, isIncludedIn([1, 2, 3])); // => false

const data = 'cat' as 'cat' | 'dog' | 'mouse';
pipe(data, isIncludedIn(['cat', 'dog'] as const)); // => true (typed "cat" | "dog");
```

### isNonNull

A function that checks if the passed parameter is not `null` and narrows its type accordingly.
Notice that `undefined` is not null!

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/is-non-null.ts#L15>

```ts
isNonNull(data)
```

**Parameters**

- `data`: The variable to check.

**Returns** `boolean` — True if the passed input is defined, false otherwise.

**Example**

```ts
isNonNull('string'); //=> true
isNonNull(null); //=> false
isNonNull(undefined); //=> true
```

### isNonNullish

A function that checks if the passed parameter is defined *AND* isn't `null`
and narrows its type accordingly.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/is-non-nullish.ts#L16>

```ts
isNonNullish(data)
```

**Parameters**

- `data`: The variable to check.

**Returns** `boolean` — True if the passed input is defined and isn't `null`, false
otherwise.

**Example**

```ts
isNonNullish('string'); //=> true
isNonNullish(null); //=> false
isNonNullish(undefined); //=> false
```

### isNot

A function that takes a guard function as predicate and returns a guard that negates it.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/is-not.ts#L17>

**Data Last**

```ts
isNot(isTruthy)(data)
```

**Parameters**

- `predicate`: The guard function to negate.

**Returns** `Function`

**Example**

```ts
isNot(isTruthy)(false); //=> true
isNot(isTruthy)(true); //=> false
```

### isNullish

A function that checks if the passed parameter is either `null` or
`undefined` and narrows its type accordingly.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/is-nullish.ts#L18>

```ts
isNullish(data)
```

**Parameters**

- `data`: The variable to check.

**Returns** `boolean` — True if the passed input is either `null` or `undefined`, false
otherwise.

**Example**

```ts
isNullish(undefined); //=> true
isNullish(null); //=> true
isNullish('somethingElse'); //=> false
```

### isNumber

A function that checks if the passed parameter is a number and narrows its
type accordingly.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/is-number.ts#L17>

```ts
isNumber(data)
```

**Parameters**

- `data`: The variable to check.

**Returns** `boolean` — True if the passed input is a number, false otherwise.

**Example**

```ts
isNumber(1); // => true
isNumber(1n); // => false
isNumber('notANumber'); // => false
```

### isObjectType

Checks if the given parameter is of type `"object"` via `typeof`, excluding `null`.

It's important to note that in JavaScript, many entities are considered objects, like Arrays, Classes, RegExps, Maps, Sets, Dates, URLs, Promise, Errors, and more. Although technically an object too, `null` is not considered an object by this function, so that its easier to narrow nullables.

For a more specific check that is limited to plain objects (simple struct/shape/record-like objects), consider using [`isPlainObject`](#isPlainObject) instead. For a simpler check that only removes `null` from the type prefer [`isNonNull`](#isNonNull) or [`isDefined`](#isDefined).

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/is-object-type.ts#L28>

**Data First**

```ts
isObjectType(data)
```

**Parameters**

- `data`: The variable to be checked for being an object type.

**Returns** `boolean` — The input type, narrowed to only objects.

**Example**

```ts
// true
isObjectType({}); //=> true
isObjectType([]); //=> true
isObjectType(Promise.resolve('something')); //=> true
isObjectType(new Date()); //=> true
isObjectType(new Error('error')); //=> true

// false
isObjectType('somethingElse'); //=> false
isObjectType(null); //=> false
```

### isPlainObject

Checks if `data` is a "plain" object. A plain object is defined as an object with string keys and values of any type, including primitives, other objects, functions, classes, etc (aka struct/shape/record/simple). Technically, a plain object is one whose prototype is either `Object.prototype` or `null`, ensuring it does not inherit properties or methods from other object types.

This function is narrower in scope than [`isObjectType`](#isObjectType), which accepts any entity considered an `"object"` by JavaScript's `typeof`.

Note that Maps, Arrays, and Sets are not considered plain objects and would return `false`.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/is-plain-object.ts#L28>

```ts
isPlainObject(data)
```

**Parameters**

- `data`: The variable to check.

**Returns** `boolean` — The input type, narrowed to only plain objects.

**Example**

```ts
// true
isPlainObject({}); //=> true
isPlainObject({ a: 123 }); //=> true

// false
isPlainObject([]); //=> false
isPlainObject(Promise.resolve('something')); //=> false
isPlainObject(new Date()); //=> false
isPlainObject(new Error('error')); //=> false
isPlainObject('somethingElse'); //=> false
isPlainObject(null); //=> false
```

### isPromise

A function that checks if the passed parameter is a Promise and narrows its type accordingly.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/is-promise.ts#L16>

```ts
isPromise(data)
```

**Parameters**

- `data`: The variable to check.

**Returns** `boolean` — True if the passed input is a Promise, false otherwise.

**Example**

```ts
isPromise(Promise.resolve(5)); //=> true
isPromise(Promise.reject(5)); //=> true
isPromise('somethingElse'); //=> false
```

### isShallowEqual

Performs a *shallow structural* comparison between two values to determine if
they are equivalent. For primitive values this is equivalent to `===`, for
arrays a **strict equality** check would be performed on every item, in
order, and for objects props will be matched and checked for **strict
equality**; Unlike [`isDeepEqual`](#isDeepEqual) where the function also *recurses* into each
item and value.

!IMPORTANT: symbol properties of objects are not supported right now and
might result in unexpected behavior. Please open an issue in the Perkakas
github project if you need support for these types.

!IMPORTANT: Promise, Date, and RegExp, are shallowly equal, even when they
are semantically different (e.g. resolved promises); but [`isDeepEqual`](#isDeepEqual) does
compare the latter 2 semantically by-value.

The result would be narrowed to the second value so that the function can be
used as a type guard.

See:
- [`isStrictEqual`](#isStrictEqual) if you don't need a deep comparison and just want to check
for simple (`===`, `Object.is`) equality.
- [`isDeepEqual`](#isDeepEqual) for a recursively deep check of arrays and objects.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/is-shallow-equal.ts#L39>

**Data First**

```ts
isShallowEqual(data, other)
```

**Parameters**

- `data`: The first value to compare.
- `other`: The second value to compare.

**Returns** `boolean`

**Example**

```ts
isShallowEqual(1, 1); //=> true
isShallowEqual(1, '1'); //=> false
isShallowEqual([1, 2, 3], [1, 2, 3]); //=> true
isShallowEqual([[1], [2], [3]], [[1], [2], [3]]); //=> false
```

**Data Last**

```ts
isShallowEqual(other)(data)
```

**Parameters**

- `other`: The second value to compare.

**Returns** `Function`

**Example**

```ts
pipe(1, isShallowEqual(1)); //=> true
pipe(1, isShallowEqual('1')); //=> false
pipe([1, 2, 3], isShallowEqual([1, 2, 3])); //=> true
pipe([[1], [2], [3]], isShallowEqual([[1], [2], [3]])); //=> false
```

### isStrictEqual

Determines whether two values are *functionally identical* in all contexts.
For primitive values (string, number), this is done by-value, and for objects
it is done by-reference (i.e., they point to the same object in memory).

Under the hood we use **both** the [`===` operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality)
and [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is). This means that `isStrictEqual(NaN, NaN) === true`
(whereas `NaN !== NaN`), and `isStrictEqual(-0, 0) === true` (whereas
`Object.is(-0, 0) === false`).

The result would be narrowed to the second value so that the function can be
used as a type guard.

See:
- [`isDeepEqual`](#isDeepEqual) for a semantic comparison that allows comparing arrays and
objects "by-value", and recurses for every item.
- [`isShallowEqual`](#isShallowEqual) if you need to compare arrays and objects "by-value" but
don't want to recurse into their values.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/is-strict-equal.ts#L33>

**Data First**

```ts
isStrictEqual(data, other)
```

**Parameters**

- `data`: The first value to compare.
- `other`: The second value to compare.

**Returns** `boolean`

**Example**

```ts
isStrictEqual(1, 1); //=> true
isStrictEqual(1, '1'); //=> false
isStrictEqual([1, 2, 3], [1, 2, 3]); //=> false
```

**Data Last**

```ts
isStrictEqual(other)(data)
```

**Parameters**

- `other`: The second value to compare.

**Returns** `Function`

**Example**

```ts
pipe(1, isStrictEqual(1)); //=> true
pipe(1, isStrictEqual('1')); //=> false
pipe([1, 2, 3], isStrictEqual([1, 2, 3])); //=> false
```

### isString

A function that checks if the passed parameter is a string and narrows its type accordingly.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/is-string.ts#L15>

```ts
isString(data)
```

**Parameters**

- `data`: The variable to check.

**Returns** `boolean` — True if the passed input is a string, false otherwise.

**Example**

```ts
isString('string'); //=> true
isString(1); //=> false
```

### isSymbol

A function that checks if the passed parameter is a symbol and narrows its type accordingly.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/is-symbol.ts#L15>

```ts
isSymbol(data)
```

**Parameters**

- `data`: The variable to check.

**Returns** `boolean` — True if the passed input is a symbol, false otherwise.

**Example**

```ts
isSymbol(Symbol('foo')); //=> true
isSymbol(1); //=> false
```

### isTruthy

A function that checks if the passed parameter is truthy and narrows its type accordingly.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/is-truthy.ts#L18>

```ts
isTruthy(data)
```

**Parameters**

- `data`: The variable to check.

**Returns** `boolean` — True if the passed input is truthy, false otherwise.

**Example**

```ts
isTruthy('somethingElse'); //=> true
isTruthy(null); //=> false
isTruthy(undefined); //=> false
isTruthy(false); //=> false
isTruthy(0); //=> false
isTruthy(''); //=> false
```

## Number

### add

Adds two numbers.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/add.ts#L16>

**Data First**

```ts
add(value, addend)
```

**Parameters**

- `value`: The number.
- `addend`: The number to add to the value.

**Returns** `bigint`

**Example**

```ts
add(10, 5); // => 15
add(10, -5); // => 5
```

**Data Last**

```ts
add(addend)(value)
```

**Parameters**

- `addend`: The number to add to the value.

**Returns** `Function`

**Example**

```ts
add(5)(10); // => 15
add(-5)(10); // => 5
map([1, 2, 3, 4], add(1)); // => [2, 3, 4, 5]
```

### ceil

Rounds up a given number to a specific precision.
If you'd like to round up to an integer (i.e. use this function with constant `precision === 0`),
use `Math.ceil` instead, as it won't incur the additional library overhead.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/ceil.ts#L21>

**Data First**

```ts
ceil(value, precision)
```

**Parameters**

- `value`: The number to round up.
- `precision`: The precision to round up to. Must be an integer between -15 and 15.

**Returns** `number`

**Example**

```ts
ceil(123.9876, 3); // => 123.988
ceil(483.22243, 1); // => 483.3
ceil(8541, -1); // => 8550
ceil(456789, -3); // => 457000
```

**Data Last**

```ts
ceil(precision)(value)
```

**Parameters**

- `precision`: The precision to round up to. Must be an integer between -15 and 15.

**Returns** `Function`

**Example**

```ts
ceil(3)(123.9876); // => 123.988
ceil(1)(483.22243); // => 483.3
ceil(-1)(8541); // => 8550
ceil(-3)(456789); // => 457000
```

### clamp

Clamp the given value within the inclusive min and max bounds.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/clamp.ts#L22>

**Data First**

```ts
clamp(value, { min, max })
```

**Parameters**

- `value`: The number.
- `limits`: The bounds limits.

**Returns** `number`

**Example**

```ts
clamp(10, { min: 20 }); // => 20
clamp(10, { max: 5 }); // => 5
clamp(10, { max: 20, min: 5 }); // => 10
```

**Data Last**

```ts
clamp({ min, max })(value)
```

**Parameters**

- `limits`: The bounds limits.

**Returns** `Function`

**Example**

```ts
clamp({ min: 20 })(10); // => 20
clamp({ max: 5 })(10); // => 5
clamp({ max: 20, min: 5 })(10); // => 10
```

### divide

Divides two numbers.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/divide.ts#L16>

**Data First**

```ts
divide(value, divisor)
```

**Parameters**

- `value`: The number.
- `divisor`: The number to divide the value by.

**Returns** `bigint`

**Example**

```ts
divide(12, 3); // => 4
reduce([1, 2, 3, 4], divide, 24); // => 1
```

**Data Last**

```ts
divide(divisor)(value)
```

**Parameters**

- `divisor`: The number to divide the value by.

**Returns** `Function`

**Example**

```ts
divide(3)(12); // => 4
map([2, 4, 6, 8], divide(2)); // => [1, 2, 3, 4]
```

### floor

Rounds down a given number to a specific precision.
If you'd like to round down to an integer (i.e. use this function with constant `precision === 0`),
use `Math.floor` instead, as it won't incur the additional library overhead.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/floor.ts#L21>

**Data First**

```ts
floor(value, precision)
```

**Parameters**

- `value`: The number to round down.
- `precision`: The precision to round down to. Must be an integer between -15 and 15.

**Returns** `number`

**Example**

```ts
floor(123.9876, 3); // => 123.987
floor(483.22243, 1); // => 483.2
floor(8541, -1); // => 8540
floor(456789, -3); // => 456000
```

**Data Last**

```ts
floor(precision)(value)
```

**Parameters**

- `precision`: The precision to round down to. Must be an integer between -15 and 15.

**Returns** `Function`

**Example**

```ts
floor(3)(123.9876); // => 123.987
floor(1)(483.22243); // => 483.2
floor(-1)(8541); // => 8540
floor(-3)(456789); // => 456000
```

### mean

Returns the mean of the elements of an array.

Only `number` arrays are supported, as `bigint` is unable to represent fractional values.

IMPORTANT: The result for empty arrays would be `undefined`, regardless of
the type of the array. This approach improves type-checking and ensures that
cases where `NaN` might occur are handled properly. To avoid adding this to
the return type for cases where the array is known to be non-empty you can use
[`hasAtLeast`](#hasAtLeast) or [`isEmpty`](#isEmpty) to guard against this case.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/mean.ts#L29>

**Data First**

```ts
mean(data)
```

**Parameters**

- `data`: The array of numbers.

**Returns** `Object`

**Example**

```ts
mean([1, 2, 3]); // => 2
mean([]); // => undefined
```

**Data Last**

```ts
mean()(data)
```

**Returns** `Function`

**Example**

```ts
pipe([1, 2, 3], mean()); // => 2
pipe([], mean()); // => undefined
```

### median

Returns the median of the elements of an array.

Only `number` arrays are supported, as `bigint` is unable to represent fractional values.

IMPORTANT: The result for empty arrays would be `undefined`, regardless of
the type of the array. This approach improves type-checking and ensures that
cases where `NaN` might occur are handled properly. To avoid adding this to
the return type for cases where the array is known to be non-empty you can use
[`hasAtLeast`](#hasAtLeast) or [`isEmpty`](#isEmpty) to guard against this case.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/median.ts#L28>

**Data First**

```ts
median(data)
```

**Parameters**

- `data`: The array of numbers.

**Returns** `Object`

**Example**

```ts
pipe([6, 10, 11], median()); // => 10
median([]); // => undefined
```

**Data Last**

```ts
median()(data)
```

**Returns** `Function`

**Example**

```ts
pipe([6, 10, 11], median()); // => 10
pipe([], median()); // => undefined
```

### multiply

Multiplies two numbers.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/multiply.ts#L16>

**Data First**

```ts
multiply(value, multiplicand)
```

**Parameters**

- `value`: The number.
- `multiplicand`: The number to multiply the value by.

**Returns** `bigint`

**Example**

```ts
multiply(3, 4); // => 12
reduce([1, 2, 3, 4], multiply, 1); // => 24
```

**Data Last**

```ts
multiply(multiplicand)(value)
```

**Parameters**

- `multiplicand`: The number to multiply the value by.

**Returns** `Function`

**Example**

```ts
multiply(4)(3); // => 12
map([1, 2, 3, 4], multiply(2)); // => [2, 4, 6, 8]
```

### product

Compute the product of the numbers in the array, or return 1 for an empty
array.

Works for both `number` and `bigint` arrays, but not arrays that contain both
types.

IMPORTANT: The result for empty arrays would be 1 (`number`) regardless of
the type of the array; to avoid adding this to the return type for cases
where the array is known to be non-empty you can use [`hasAtLeast`](#hasAtLeast) or
[`isEmpty`](#isEmpty) to guard against this case.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/product.ts#L39>

**Data First**

```ts
product(data)
```

**Parameters**

- `data`: The array of numbers.

**Returns** `Object`

**Example**

```ts
product([1, 2, 3]); // => 6
product([1n, 2n, 3n]); // => 6n
product([]); // => 1
```

**Data Last**

```ts
product()(data)
```

**Returns** `Function`

**Example**

```ts
pipe([1, 2, 3], product()); // => 6
pipe([1n, 2n, 3n], product()); // => 6n
pipe([], product()); // => 1
```

### randomBigInt

Generate a random `bigint` between `from` and `to` (inclusive).

! Important: In most environments this function uses
[`crypto.getRandomValues()`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues)
under-the-hood which **is** cryptographically strong. When the WebCrypto API
isn't available (Node 18) we fallback to an implementation that uses
[`Math.random()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random)
which is **NOT** cryptographically secure.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/random-big-int.ts#L21>

**Data First**

```ts
randomBigInt(from, to)
```

**Parameters**

- `from`: The minimum value.
- `to`: The maximum value.

**Returns** `bigint` — The random integer.

**Example**

```ts
randomBigInt(1n, 10n); // => 5n
```

### randomInteger

Generate a random integer between `from` and `to` (inclusive).

!Important: This function uses [`Math.random()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random) under-the-hood, which has two major limitations:
1. It generates 2^52 possible values, so the bigger the range, the less
uniform the distribution of values would be, and at ranges larger than that
some values would never come up.
2. It is not cryptographically secure and should not be used for security
scenarios.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/random-integer.ts#L47>

**Data First**

```ts
randomInteger(from, to)
```

**Parameters**

- `from`: The minimum value.
- `to`: The maximum value.

**Returns** `Object` — The random integer.

**Example**

```ts
randomInteger(1, 10); // => 5
randomInteger(1.5, 2.6); // => 2
```

### round

Rounds a given number to a specific precision.
If you'd like to round to an integer (i.e. use this function with constant `precision === 0`),
use `Math.round` instead, as it won't incur the additional library overhead.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/round.ts#L21>

**Data First**

```ts
round(value, precision)
```

**Parameters**

- `value`: The number to round.
- `precision`: The precision to round to. Must be an integer between -15 and 15.

**Returns** `number`

**Example**

```ts
round(123.9876, 3); // => 123.988
round(483.22243, 1); // => 483.2
round(8541, -1); // => 8540
round(456789, -3); // => 457000
```

**Data Last**

```ts
round(precision)(value)
```

**Parameters**

- `precision`: The precision to round to. Must be an integer between -15 and 15.

**Returns** `Function`

**Example**

```ts
round(3)(123.9876); // => 123.988
round(1)(483.22243); // => 483.2
round(-1)(8541); // => 8540
round(-3)(456789); // => 457000
```

### subtract

Subtracts two numbers.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/subtract.ts#L17>

**Data First**

```ts
subtract(value, subtrahend)
```

**Parameters**

- `value`: The number.
- `subtrahend`: The number to subtract from the value.

**Returns** `bigint`

**Example**

```ts
subtract(10, 5); // => 5
subtract(10, -5); // => 15
reduce([1, 2, 3, 4], subtract, 20); // => 10
```

**Data Last**

```ts
subtract(subtrahend)(value)
```

**Parameters**

- `subtrahend`: The number to subtract from the value.

**Returns** `Function`

**Example**

```ts
subtract(5)(10); // => 5
subtract(-5)(10); // => 15
map([1, 2, 3, 4], subtract(1)); // => [0, 1, 2, 3]
```

### sum

Sums the numbers in the array, or return 0 for an empty array.

Works for both `number` and `bigint` arrays, but not arrays that contain both
types.

IMPORTANT: The result for empty arrays would be 0 (`number`) regardless of
the type of the array; to avoid adding this to the return type for cases
where the array is known to be non-empty you can use [`hasAtLeast`](#hasAtLeast) or
[`isEmpty`](#isEmpty) to guard against this case.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/sum.ts#L38>

**Data First**

```ts
sum(data)
```

**Parameters**

- `data`: The array of numbers.

**Returns** `Object`

**Example**

```ts
sum([1, 2, 3]); // => 6
sum([1n, 2n, 3n]); // => 6n
sum([]); // => 0
```

**Data Last**

```ts
sum()(data)
```

**Returns** `Function`

**Example**

```ts
pipe([1, 2, 3], sum()); // => 6
pipe([1n, 2n, 3n], sum()); // => 6n
pipe([], sum()); // => 0
```

## Object

### addProp

Add a new property to an object.

The function doesn't do any checks on the input object. If the property
already exists it will be overwritten, and the type of the new value is not
checked against the previous type.

Use [`set`](#set) to override values explicitly with better protections.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/add-prop.ts#L23>

**Data First**

```ts
addProp(obj, prop, value)
```

**Parameters**

- `obj`: The target object.
- `prop`: The property name.
- `value`: The property value.

**Returns** `Object`

**Example**

```ts
addProp({ firstName: 'john' }, 'lastName', 'doe'); // => {firstName: 'john', lastName: 'doe'}
```

**Data Last**

```ts
addProp(prop, value)(obj)
```

**Parameters**

- `prop`: The property name.
- `value`: The property value.

**Returns** `Function`

**Example**

```ts
addProp('lastName', 'doe')({ firstName: 'john' }); // => {firstName: 'john', lastName: 'doe'}
```

### clone

Creates a deep copy of the value. Supported types: [plain objects](#isPlainObject),
`Array`, `number`, `string`, `boolean`, `Date`, and `RegExp`. Functions are
assigned by reference rather than copied. Class instances or any other
built-in type that isn't mentioned above are not supported (but might
work).

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/clone.ts#L18>

**Data First**

```ts
clone(data)
```

**Parameters**

- `data`: The object to clone.

**Returns** `Object`

**Example**

```ts
clone({ foo: 'bar' }); // {foo: 'bar'}
```

**Data Last**

```ts
clone()(data)
```

**Returns** `Function`

**Example**

```ts
pipe({ foo: 'bar' }, clone()); // {foo: 'bar'}
```

### entries

Returns an array of key/values of the enumerable properties of an object.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/entries.ts#L34>

**Data First**

```ts
entries(object)
```

**Parameters**

- `data`: Object to return keys and values of.

**Returns** `Array`

**Example**

```ts
entries({ a: 1, b: 2, c: 3 }); // => [['a', 1], ['b', 2], ['c', 3]]
```

**Data Last**

```ts
entries()(object)
```

**Returns** `Function`

**Example**

```ts
pipe({ a: 1, b: 2, c: 3 }, entries()); // => [['a', 1], ['b', 2], ['c', 3]]
```

### evolve

Creates a new object by applying functions that is included in `evolver` object parameter
to the `data` object parameter according to their corresponding path.

Functions included in `evolver` object will not be invoked
if its corresponding key does not exist in the `data` object.
Also, values included in `data` object will be kept as is
if its corresponding key does not exist in the `evolver` object.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/evolve.ts#L92>

**Data First**

```ts
evolve(data, evolver)
```

**Parameters**

- `object`: Object whose value is applied to the corresponding function
that is defined in `evolver` at the same path.
- `evolver`: Object that include functions that is applied to
the corresponding value of `data` object at the same path.

**Returns** `Object`

**Example**

```ts
const evolver = {
  count: add(1),
  time: { elapsed: add(1), remaining: add(-1) },
};
const data = {
  id: 10,
  count: 10,
  time: { elapsed: 100, remaining: 1400 },
};
evolve(data, evolver);
// => {
//   id: 10,
//   count: 11,
//   time: { elapsed: 101, remaining: 1399 },
// }
```

**Data Last**

```ts
evolve(evolver)(data)
```

**Parameters**

- `evolver`: Object that include functions that is applied to
the corresponding value of `data` object at the same path.

**Returns** `Function`

**Example**

```ts
const evolver = {
  count: add(1),
  time: { elapsed: add(1), remaining: add(-1) },
};
const data = {
  id: 10,
  count: 10,
  time: { elapsed: 100, remaining: 1400 },
};
pipe(data, evolve(evolver));
// => {
//   id: 10,
//   count: 11,
//   time: { elapsed: 101, remaining: 1399 },
// }
```

### forEachObj

Iterate an object using a defined callback function.

The dataLast version returns the original object (instead of not returning
anything (`void`)) to allow using it in a pipe. The returned object is the
same reference as the input object, and not a shallow copy of it!

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/for-each-obj.ts#L23>

**Data First**

```ts
forEachObj(object, fn)
```

**Parameters**

- `data`: The object who'se entries would be iterated on.
- `callbackfn`: A function to execute for each element in the array.

**Returns** `void`

**Example**

```ts
forEachObj({ a: 1 }, (val, key, obj) => {
  console.log(`${key}: ${val}`);
}); // "a: 1"
```

**Data Last**

```ts
forEachObj(fn)(object)
```

**Parameters**

- `callbackfn`: A function to execute for each element in the array.

**Returns** `Function` — The original object (the ref itself, not a shallow copy of it).

**Example**

```ts
pipe(
  { a: 1 },
  forEachObj((val, key) => console.log(`${key}: ${val}`)),
); // "a: 1"
```

### fromEntries

Creates a new object from an array of tuples by pairing up first and second elements as {[key]: value}.
If a tuple is not supplied for any element in the array, the element will be ignored
If duplicate keys exist, the tuple with the greatest index in the input array will be preferred.

The strict option supports more sophisticated use-cases like those that would
result when calling the strict `toPairs` function.

There are several other functions that could be used to build an object from
an array:
[`fromKeys`](#fromKeys) - Builds an object from an array of *keys* and a mapper for values.
[`indexBy`](#indexBy) - Builds an object from an array of *values* and a mapper for keys.
[`pullObject`](#pullObject) - Builds an object from an array of items with mappers for *both* keys and values.
Refer to the docs for more details.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/from-entries.ts#L111>

**Data First**

```ts
fromEntries(tuples)
```

**Parameters**

- `entries`: An array of key-value pairs.

**Returns** `Object`

**Example**

```ts
fromEntries([
  ['a', 'b'],
  ['c', 'd'],
]); // => {a: 'b', c: 'd'}
```

**Data Last**

```ts
fromEntries()(tuples)
```

**Returns** `Function`

**Example**

```ts
pipe(
  [
    ['a', 'b'],
    ['c', 'd'],
  ] as const,
  fromEntries(),
); // => {a: 'b', c: 'd'}
```

### fromKeys

Creates an object that maps each key in `data` to the result of `mapper` for
that key. Duplicate keys are overwritten, guaranteeing that `mapper` is run
for each item in `data`.

There are several other functions that could be used to build an object from
an array:
[`indexBy`](#indexBy) - Builds an object from an array of *values* and a mapper for keys.
[`pullObject`](#pullObject) - Builds an object from an array of items with mappers for *both* keys and values.
[`fromEntries`](#fromEntries) - Builds an object from an array of key-value pairs.
Refer to the docs for more details.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/from-keys.ts#L44>

**Data First**

```ts
fromKeys(data, mapper)
```

**Parameters**

- `data`: An array of keys of the output object. All items in the array
would be keys in the output array.
- `mapper`: Takes a key and returns the value that would be associated
with that key.

**Returns** `Object`

**Example**

```ts
fromKeys(['cat', 'dog'], length()); // { cat: 3, dog: 3 } (typed as Partial<Record<"cat" | "dog", number>>)
fromKeys([1, 2], add(1)); // { 1: 2, 2: 3 } (typed as Partial<Record<1 | 2, number>>)
```

**Data Last**

```ts
fromKeys(mapper)(data)
```

**Parameters**

- `mapper`: Takes a key and returns the value that would be associated
with that key.

**Returns** `Function`

**Example**

```ts
pipe(['cat', 'dog'], fromKeys(length())); // { cat: 3, dog: 3 } (typed as Partial<Record<"cat" | "dog", number>>)
pipe([1, 2], fromKeys(add(1))); // { 1: 2, 2: 3 } (typed as Partial<Record<1 | 2, number>>)
```

### invert

Returns an object whose keys and values are swapped. If the object contains duplicate values,
subsequent values will overwrite previous values.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/invert.ts#L25>

**Data First**

```ts
invert(object)
```

**Parameters**

- `object`: The object.

**Returns** `Object`

**Example**

```ts
invert({ a: 'd', b: 'e', c: 'f' }); // => { d: "a", e: "b", f: "c" }
```

**Data Last**

```ts
invert()(object)
```

**Returns** `Function`

**Example**

```ts
pipe({ a: 'd', b: 'e', c: 'f' }, invert()); // => { d: "a", e: "b", f: "c" }
```

### keys

Returns a new array containing the keys of the array or object.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/keys.ts#L68>

**Data First**

```ts
keys(source)
```

**Parameters**

- `data`: Either an array or an object.

**Returns** `Object`

**Example**

```ts
keys(['x', 'y', 'z']); // => ['0', '1', '2']
keys({ a: 'x', b: 'y', 5: 'z' }); // => ['a', 'b', '5']
```

**Data Last**

```ts
keys()(source)
```

**Returns** `Function`

**Example**

```ts
pipe(['x', 'y', 'z'], keys()); // => ['0', '1', '2']
pipe({ a: 'x', b: 'y', 5: 'z' } as const, keys()); // => ['a', 'b', '5']
```

### mapKeys

Maps keys of `object` and keeps the same values.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/map-keys.ts#L61>

**Data First**

```ts
mapKeys(object, fn)
```

**Parameters**

- `data`: The object to map.
- `keyMapper`: The mapping function.

**Returns** `Object`

**Example**

```ts
mapKeys({ a: 1, b: 2 }, (key, value) => key + value); // => { a1: 1, b2: 2 }
```

**Data Last**

```ts
mapKeys(fn)(object)
```

**Parameters**

- `keyMapper`: The mapping function.

**Returns** `Function`

**Example**

```ts
pipe(
  { a: 1, b: 2 },
  mapKeys((key, value) => key + value),
); // => { a1: 1, b2: 2 }
```

### mapValues

Maps values of `object` and keeps the same keys. Symbol keys are not passed
to the mapper and will be removed from the output object.

To also copy the symbol keys to the output use merge:
`merge(data, mapValues(data, mapper))`).

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/map-values.ts#L26>

**Data First**

```ts
mapValues(data, mapper)
```

**Parameters**

- `data`: The object to map.
- `valueMapper`: The mapping function.

**Returns** `Object`

**Example**

```ts
mapValues({ a: 1, b: 2 }, (value, key) => value + key); // => {a: '1a', b: '2b'}
```

**Data Last**

```ts
mapValues(mapper)(data)
```

**Parameters**

- `valueMapper`: The mapping function.

**Returns** `Function`

**Example**

```ts
pipe(
  { a: 1, b: 2 },
  mapValues((value, key) => value + key),
); // => {a: '1a', b: '2b'}
```

### merge

Merges two objects into one by combining their properties, effectively
creating a new object that incorporates elements from both. The merge
operation prioritizes the second object's properties, allowing them to
overwrite those from the first object with the same names.

Equivalent to `{ ...data, ...source }`.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/merge.ts#L28>

**Data First**

```ts
merge(data, source)
```

**Parameters**

- `data`: The destination object, serving as the basis for the merge.
Properties from this object are included in the new object, but will be
overwritten by properties from the source object with matching keys.
- `source`: The source object, whose properties will be included in the
new object. If properties in this object share keys with properties in the
destination object, the values from the source object will be used in the
new object.

**Returns** `Object` — An object fully containing `source`, and any properties from `data`
that don't share a name with any property in `source`.

**Example**

```ts
merge({ x: 1, y: 2 }, { y: 10, z: 2 }); // => { x: 1, y: 10, z: 2 }
```

**Data Last**

```ts
merge(source)(data)
```

**Parameters**

- `source`: The source object, whose properties will be included in the
new object. If properties in this object share keys with properties in the
destination object, the values from the source object will be used in the
new object.

**Returns** `Function` — An object fully containing `source`, and any properties from `data`
that don't share a name with any property in `source`.

**Example**

```ts
pipe({ x: 1, y: 2 }, merge({ y: 10, z: 2 })); // => { x: 1, y: 10, z: 2 }
```

### mergeDeep

Merges the `source` object into the `destination` object. The merge is similar to performing `{ ...destination, ... source }` (where disjoint values from each object would be copied as-is, and for any overlapping props the value from `source` would be used); But for *each prop* (`p`), if **both** `destination` and `source` have a **plain-object** as a value, the value would be taken as the result of recursively deepMerging them (`result.p === deepMerge(destination.p, source.p)`).

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/merge-deep.ts#L18>

**Data First**

```ts
mergeDeep(destination, source)
```

**Parameters**

- `destination`: The object to merge into. In general, this object would have it's values overridden.
- `source`: The object to merge from. In general, shared keys would be taken from this object.

**Returns** `Object` — The merged object.

**Example**

```ts
mergeDeep({ foo: 'bar', x: 1 }, { foo: 'baz', y: 2 }); // => { foo: 'baz', x: 1, y: 2 }
```

**Data Last**

```ts
mergeDeep(source)(destination)
```

**Parameters**

- `source`: The object to merge from. In general, shared keys would be taken from this object.

**Returns** `Function` — The merged object.

**Example**

```ts
pipe({ foo: 'bar', x: 1 }, mergeDeep({ foo: 'baz', y: 2 })); // => { foo: 'baz', x: 1, y: 2 }
```

### objOf

Creates an object containing a single `key:value` pair.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/obj-of.ts#L14>

```ts
objOf(value, key)
```

**Parameters**

- `value`: The object value.
- `key`: The property name.

**Returns** `Record`

**Example**

```ts
objOf(10, 'a'); // => { a: 10 }
```

```ts
objOf(key)(value)
```

**Parameters**

- `key`: The property name.

**Returns** `Function`

**Example**

```ts
pipe(10, objOf('a')); // => { a: 10 }
```

### omit

Returns a partial copy of an object omitting the keys specified.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/omit.ts#L106>

**Data First**

```ts
omit(obj, keys)
```

**Parameters**

- `data`: The object.
- `keys`: The property names.

**Returns** `Object`

**Example**

```ts
omit({ a: 1, b: 2, c: 3, d: 4 }, ['a', 'd']); // => { b: 2, c: 3 }
```

**Data Last**

```ts
omit(keys)(obj)
```

**Parameters**

- `keys`: The property names.

**Returns** `Function`

**Example**

```ts
pipe({ a: 1, b: 2, c: 3, d: 4 }, omit(['a', 'd'])); // => { b: 2, c: 3 }
```

### omitBy

Creates a shallow copy of the data, and then removes any keys that the
predicate rejects. Symbol keys are not passed to the predicate and would be
passed through to the output as-is.

See [`pickBy`](#pickBy) for a complementary function which starts with an empty object
and adds the entries that the predicate accepts. Because it is additive,
symbol keys will not be passed through to the output object.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/omit-by.ts#L116>

**Data First**

```ts
omitBy(data, predicate)
```

**Parameters**

- `data`: The target object.
- `predicate`: A function that takes the value, key, and the data itself
and returns `true` if the entry shouldn't be part of the output object, or
`false` to keep it. If the function is a type-guard on the value the output
type would be narrowed accordingly.

**Returns** `Object` — A shallow copy of the input object with the rejected entries
removed.

**Example**

```ts
omitBy({ a: 1, b: 2, A: 3, B: 4 }, (val, key) => key.toUpperCase() === key); // => {a: 1, b: 2}
```

**Data Last**

```ts
omitBy(fn)(object)
```

**Parameters**

- `predicate`: The predicate.

**Returns** `Function`

**Example**

```ts
omitBy((val, key) => key.toUpperCase() === key)({ a: 1, b: 2, A: 3, B: 4 }); // => {a: 1, b: 2}
```

### pathOr (deprecated)

Gets the value at `path` of `object`. If the resolved value is `null` or `undefined`, the `defaultValue` is returned in its place.

**DEPRECATED**: Use `defaultTo(prop(object, ...path), defaultValue)`
instead!

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/path-or.ts#L88>

**Data First**

```ts
pathOr(object, array, defaultValue)
```

**Parameters**

- `object`: The target object.
- `path`: The path of the property to get.
- `defaultValue`: The default value.

**Returns** `Object`

**Example**

```ts
pathOr({ x: 10 }, ['y'], 2); // 2
pathOr({ y: 10 }, ['y'], 2); // 10
```

**Data Last**

```ts
pathOr(array, defaultValue)(object)
```

**Parameters**

- `path`: The path of the property to get.
- `defaultValue`: The default value.

**Returns** `Function`

**Example**

```ts
pipe({ x: 10 }, pathOr(['y'], 2)); // 2
pipe({ y: 10 }, pathOr(['y'], 2)); // 10
```

### pick

Creates an object composed of the picked `data` properties.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/pick.ts#L93>

**Data First**

```ts
pick(object, [prop1, prop2])
```

**Parameters**

- `data`: The target object.
- `keys`: The property names.

**Returns** `Object`

**Example**

```ts
pick({ a: 1, b: 2, c: 3, d: 4 }, ['a', 'd']); // => { a: 1, d: 4 }
```

**Data Last**

```ts
pick([prop1, prop2])(object)
```

**Parameters**

- `keys`: The property names.

**Returns** `Function`

**Example**

```ts
pipe({ a: 1, b: 2, c: 3, d: 4 }, pick(['a', 'd'])); // => { a: 1, d: 4 }
```

### pickBy

Iterates over the entries of `data` and reconstructs the object using only
entries that `predicate` accepts. Symbol keys are not passed to the predicate
and would be filtered out from the output object.

See [`omitBy`](#omitBy) for a complementary function which starts with a shallow copy of
the input object and removes the entries that the predicate rejects. Because
it is subtractive symbol keys would be copied over to the output object.
See also [`entries`](#entries), [`filter`](#filter), and [`fromEntries`](#fromEntries) which could be used to build
your own version of [`pickBy`](#pickBy) if you need more control (though the resulting
type might be less precise).

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/pick-by.ts#L129>

**Data First**

```ts
pickBy(data, predicate)
```

**Parameters**

- `data`: The target object.
- `predicate`: A function that takes the value, key, and the data itself
and returns true if the entry should be part of the output object, or `false`
to remove it. If the function is a type-guard on the value the output type
would be narrowed accordingly.

**Returns** `Object` — A shallow copy of the input object with the rejected entries
removed.

**Example**

```ts
pickBy({ a: 1, b: 2, A: 3, B: 4 }, (val, key) => key.toUpperCase() === key); // => {A: 3, B: 4}
```

**Data Last**

```ts
pickBy(predicate)(data)
```

**Parameters**

- `predicate`: A function that takes the value, key, and the data itself
and returns true if the entry should be part of the output object, or `false`
to remove it. If the function is a type-guard on the value the output type
would be narrowed accordingly.

**Returns** `Function`

**Example**

```ts
pipe(
  { a: 1, b: 2, A: 3, B: 4 },
  pickBy((val, key) => key.toUpperCase() === key),
); // => {A: 3, B: 4}
```

### prop

Gets the value of the given property from an object. Nested properties can
be accessed by providing a variadic array of keys that define the path from
the root to the desired property. Arrays can be accessed by using numeric
keys. Unions, optional properties, and index signatures are handled
gracefully by returning `undefined` early for any non-existing property on
the path. Paths are validated against the object type to provide stronger
type safety, better compile-time errors, and to enable autocompletion in
IDEs.

To check whether a key exists on the object, use [`hasProp`](#hasProp).

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/prop.ts#L72>

**Data First**

```ts
prop(data, ...keys)
```

**Parameters**

- `data`: The object or array to access.
- `key`: The key(s) for the property to extract.

**Returns** `Object`

**Example**

```ts
prop({ foo: { bar: 'baz' } }, 'foo'); //=> { bar: 'baz' }
prop({ foo: { bar: 'baz' } }, 'foo', 'bar'); //=> 'baz'
prop(['cat', 'dog'], 1); //=> 'dog'
```

**Data Last**

```ts
prop(...keys)(data)
```

**Parameters**

- `key`: The key(s) for the property to extract.

**Returns** `Function`

**Example**

```ts
pipe({ foo: { bar: 'baz' } }, prop('foo')); //=> { bar: 'baz' }
pipe({ foo: { bar: 'baz' } }, prop('foo', 'bar')); //=> 'baz'
pipe(['cat', 'dog'], prop(1)); //=> 'dog'
```

### pullObject

Creates an object that maps the result of `valueExtractor` with a key
resulting from running `keyExtractor` on each item in `data`. Duplicate keys
are overwritten, guaranteeing that the extractor functions are run on each
item in `data`.

There are several other functions that could be used to build an object from
an array:
[`fromKeys`](#fromKeys) - Builds an object from an array of *keys* and a mapper for values.
[`indexBy`](#indexBy) - Builds an object from an array of *values* and a mapper for keys.
[`fromEntries`](#fromEntries) - Builds an object from an array of key-value pairs.
Refer to the docs for more details.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/pull-object.ts#L35>

**Data First**

```ts
pullObject(data, keyExtractor, valueExtractor)
```

**Parameters**

- `data`: The items used to pull/extract the keys and values from.
- `keyExtractor`: Computes the key for item.
- `valueExtractor`: Computes the value for the item.

**Returns** `Object`

**Example**

```ts
pullObject(
  [
    { name: 'john', email: 'john@perkakas.com' },
    { name: 'jane', email: 'jane@perkakas.com' },
  ],
  prop('name'),
  prop('email'),
); // => { john: "john@perkakas.com", jane: "jane@perkakas.com" }
```

**Data Last**

```ts
pullObject(keyExtractor, valueExtractor)(data)
```

**Parameters**

- `keyExtractor`: Computes the key for item.
- `valueExtractor`: Computes the value for the item.

**Returns** `Function`

**Example**

```ts
pipe(
  [
    { name: 'john', email: 'john@perkakas.com' },
    { name: 'jane', email: 'jane@perkakas.com' },
  ],
  pullObject(prop('name'), prop('email')),
); // => { john: "john@perkakas.com", jane: "jane@perkakas.com" }
```

### set

Sets the `value` at [`prop`](#prop) of `object`.

To add a new property to an object, or to override its type, use [`addProp`](#addProp)
instead, and to set a property within a nested object use [`setPath`](#setPath).

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/set.ts#L20>

**Data First**

```ts
set(obj, prop, value)
```

**Parameters**

- `obj`: The target method.
- `prop`: The property name.
- `value`: The value to set.

**Returns** `Object`

**Example**

```ts
set({ a: 1 }, 'a', 2); // => { a: 2 }
```

**Data Last**

```ts
set(prop, value)(obj)
```

**Parameters**

- `prop`: The property name.
- `value`: The value to set.

**Returns** `Function`

**Example**

```ts
pipe({ a: 1 }, set('a', 2)); // => { a: 2 }
```

### setPath

Sets the value at `path` of `object`.

For simple cases where the path is only one level deep, prefer [`set`](#set) instead.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/set-path.ts#L57>

**Data First**

```ts
setPath(obj, path, value)
```

**Parameters**

- `data`: The target method.
- `path`: The array of properties.
- `value`: The value to set.

**Returns** `Object`

**Example**

```ts
setPath({ a: { b: 1 } }, ['a', 'b'], 2); // => { a: { b: 2 } }
```

**Data Last**

```ts
setPath(path, value)(obj)
```

**Parameters**

- `path`: The array of properties.
- `value`: The value to set.

**Returns** `Function`

**Example**

```ts
pipe({ a: { b: 1 } }, setPath(['a', 'b'], 2)); // { a: { b: 2 } }
```

### swapProps

Swaps the values of two properties in an object based on the provided keys.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/swap-props.ts#L21>

**Data First**

```ts
swapProps(data, key1, key2)
```

**Parameters**

- `data`: The object to be manipulated.
- `key1`: The first property key.
- `key2`: The second property key.

**Returns** `Object` — Returns the manipulated object.

**Example**

```ts
swapProps({ a: 1, b: 2, c: 3 }, 'a', 'b'); // => {a: 2, b: 1, c: 3}
```

**Data Last**

```ts
swapProps(key1, key2)(data)
```

**Parameters**

- `key1`: The first property key.
- `key2`: The second property key.

**Returns** `Function` — Returns the manipulated object.

**Example**

```ts
swapProps('a', 'b')({ a: 1, b: 2, c: 3 }); // => {a: 2, b: 1, c: 3}
```

### values

Returns a new array containing the values of the array or object.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/values.ts#L21>

**Data First**

```ts
values(source)
```

**Parameters**

- `data`: Either an array or an object.

**Returns** `Object`

**Example**

```ts
values(['x', 'y', 'z']); // => ['x', 'y', 'z']
values({ a: 'x', b: 'y', c: 'z' }); // => ['x', 'y', 'z']
```

**Data Last**

```ts
values()(source)
```

**Returns** `Function`

**Example**

```ts
pipe(['x', 'y', 'z'], values()); // => ['x', 'y', 'z']
pipe({ a: 'x', b: 'y', c: 'z' }, values()); // => ['x', 'y', 'z']
pipe({ a: 'x', b: 'y', c: 'z' }, values(), first()); // => 'x'
```

## String

### capitalize

Makes the first character of a string uppercase while leaving the rest
unchanged.

It uses the built-in [`String.prototype.toUpperCase`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase)
for the runtime and the built-in [`Capitalize`](https://www.typescriptlang.org/docs/handbook/2/template-literal-types.html#capitalizestringtype)
utility type for typing and thus shares their _[locale inaccuracies](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLocaleUpperCase#description)_.

For display purposes, prefer using the CSS pseudo-element [`::first-letter`](https://developer.mozilla.org/en-US/docs/Web/CSS/::first-letter) to target
just the first letter of the word, and [`text-transform: uppercase`](https://developer.mozilla.org/en-US/docs/Web/CSS/text-transform#uppercase)
to capitalize it. This transformation **is** locale-aware.

For other case manipulations see: [`toUpperCase`](#toUpperCase), [`toLowerCase`](#toLowerCase),
[`uncapitalize`](#uncapitalize), [`toCamelCase`](#toCamelCase), [`toKebabCase`](#toKebabCase), [`toSnakeCase`](#toSnakeCase), and
[`toTitleCase`](#toTitleCase).

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/capitalize.ts#L27>

**Data First**

```ts
capitalize(data)
```

**Parameters**

- `data`: A string.

**Returns** `Object`

**Example**

```ts
capitalize('hello world'); // "Hello world"
```

**Data Last**

```ts
capitalize()(data)
```

**Returns** `Function`

**Example**

```ts
pipe('hello world', capitalize()); // "Hello world"
```

### endsWith

Determines whether a string ends with the provided suffix, and refines the
output type if possible.

This function is a wrapper around the built-in [`String.prototype.endsWith`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith)
method, but doesn't expose the `endPosition` parameter. To check only up to a
specific position, use `endsWith(sliceString(data, 0, endPosition), suffix)`.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/ends-with.ts#L146>

**Data First**

```ts
endsWith(data, suffix)
```

**Parameters**

- `data`: The input string.
- `suffix`: The string to check for at the end.

**Returns** `boolean`

**Example**

```ts
endsWith('hello world', 'world'); //=> true
endsWith('hello world' as string, 'hello'); //=> false
```

**Data Last**

```ts
endsWith(suffix)(data)
```

**Parameters**

- `suffix`: The string to check for at the end.

**Returns** `Function`

**Example**

```ts
pipe('hello world', endsWith('world')); //=> true
pipe('hello world', endsWith('hello')); //=> false
```

### humanReadableFileSize

Returns human readable file size.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/human-readable-file-size.ts#L13>

```ts
humanReadableFileSize(bytes, base)
```

**Parameters**

- `bytes`: the file size in bytes
- `base` (optional): the base (1000 or 1024)

**Returns** `string`

**Example**

```ts
humanReadableFileSize(1000); // => '1.0 kB'
humanReadableFileSize(2097152, 1024); // => '2.0 MiB'
```

### randomString

A [pseudo-random](https://en.wikipedia.org/wiki/Pseudorandom_number_generator) [alpha-numeric](https://en.wikipedia.org/wiki/Alphanumericals)
[string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String).

It is not [cryptographically secure](https://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator)!

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/random-string.ts#L21>

**Data First**

```ts
randomString(length)
```

**Parameters**

- `length`: The length of the random string.

**Returns** `string` — The random string.

**Example**

```ts
randomString(5); // => aB92J
```

**Data Last**

```ts
randomString()(length)
```

**Returns** `Function` — The random string.

**Example**

```ts
pipe(5, randomString()); // => aB92J
```

### sliceString

Extracts a section of a string between two indices.

This function is a wrapper around the built-in [`String.prototype.slice`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice)
method.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/slice-string.ts#L21>

**Data First**

```ts
sliceString(data, indexStart, indexEnd)
```

**Parameters**

- `data`: The string to extract from.
- `indexStart`: The index of the first character to include in the
returned substring.
- `indexEnd` (optional): The index of the first character to exclude from the
returned substring.

**Returns** `string` — A new string containing the extracted section of the string.

**Example**

```ts
sliceString('abcdefghijkl', 1); // => `bcdefghijkl`
sliceString('abcdefghijkl', 4, 7); // => `efg`
```

**Data Last**

```ts
sliceString(indexStart, indexEnd)(string)
```

**Parameters**

- `indexStart`: The index of the first character to include in the
returned substring.
- `indexEnd` (optional): The index of the first character to exclude from the
returned substring, or `undefined` for the rest of the string.

**Returns** `Function` — A new string containing the extracted section of the string.

**Example**

```ts
sliceString(1)('abcdefghijkl'); // => `bcdefghijkl`
sliceString(4, 7)('abcdefghijkl'); // => `efg`
```

### slugify

Turn any string into a URL/DOM safe string.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/slugify.ts#L11>

```ts
slugify(str)
```

**Parameters**

- `str`: the string to slugify

**Returns** `string`

**Example**

```ts
slugify('FooBar'); // => 'foobar'
slugify('This!-is*&%#@^up!'); // => 'this-is-up'
```

### split

Splits a string into an array of substrings using a separator pattern.

This function is a wrapper around the built-in [`String.prototype.split`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split)
method.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/split.ts#L56>

**Data First**

```ts
split(data, separator, limit)
```

**Parameters**

- `data`: The string to split.
- `separator`: The pattern describing where each split should occur. Can
be a string, or a regular expression.
- `limit` (optional): A non-negative integer specifying a limit on the number of
substrings to be included in the array. If provided, splits the string at
each occurrence of the specified separator, but stops when limit entries have
been placed in the array. Any leftover text is not included in the array at
all. The array may contain fewer entries than limit if the end of the string
is reached before the limit is reached. If limit is 0, [] is returned.

**Returns** `Array` — An array of strings, split at each point where the separator occurs
in the given string.

**Example**

```ts
split('a,b,c', ','); //=> ["a", "b", "c"]
split('a,b,c', ',', 2); //=> ["a", "b"]
split('a1b2c3d', /\d/u); //=> ["a", "b", "c", "d"]
```

**Data Last**

```ts
split(separator, limit)(data)
```

**Parameters**

- `separator`: The pattern describing where each split should occur. Can
be a string, or a regular expression.
- `limit` (optional): A non-negative integer specifying a limit on the number of
substrings to be included in the array. If provided, splits the string at
each occurrence of the specified separator, but stops when limit entries have
been placed in the array. Any leftover text is not included in the array at
all. The array may contain fewer entries than limit if the end of the string
is reached before the limit is reached. If limit is 0, [] is returned.

**Returns** `Function` — An array of strings, split at each point where the separator occurs
in the given string.

**Example**

```ts
pipe('a,b,c', split(',')); //=> ["a", "b", "c"]
pipe('a,b,c', split(',', 2)); //=> ["a", "b"]
pipe('a1b2c3d', split(/\d/u)); //=> ["a", "b", "c", "d"]
```

### startsWith

Determines whether a string begins with the provided prefix, and refines the
output type if possible.

This function is a wrapper around the built-in [`String.prototype.startsWith`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith)
method, but doesn't expose the `position` parameter. To check from a specific
position, use `startsWith(sliceString(data, position), prefix)`.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/starts-with.ts#L146>

**Data First**

```ts
startsWith(data, prefix)
```

**Parameters**

- `data`: The input string.
- `prefix`: The string to check for at the beginning.

**Returns** `boolean`

**Example**

```ts
startsWith('hello world', 'hello'); //=> true
startsWith('hello world' as string, 'world'); //=> false
```

**Data Last**

```ts
startsWith(prefix)(data)
```

**Parameters**

- `prefix`: The string to check for at the beginning.

**Returns** `Function`

**Example**

```ts
pipe('hello world', startsWith('hello')); //=> true
pipe('hello world', startsWith('world')); //=> false
```

### toCamelCase

Converts text to **camelCase** by splitting it into words, lowercasing the
first word, capitalizing the rest, then joining them back together.

Because it uses the built-in case conversion methods, the function shares
their _[locale inaccuracies](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLocaleLowerCase#description)_
too, making it best suited for simple strings like identifiers and internal
keys. For linguistic text processing, use [`Intl.Segmenter`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter)
with [`granularity: "word"`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter#parameters),
[`toLocaleLowerCase`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLocaleLowerCase),
and [`toLocaleUpperCase`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLocaleUpperCase)
which are purpose-built to handle nuances in languages and locales.

For other case manipulations see: [`toLowerCase`](#toLowerCase), [`toUpperCase`](#toUpperCase), [`capitalize`](#capitalize),
[`uncapitalize`](#uncapitalize), [`toKebabCase`](#toKebabCase), [`toSnakeCase`](#toSnakeCase), and [`toTitleCase`](#toTitleCase).

For *PascalCase* use `capitalize(toCamelCase(data))`.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/to-camel-case.ts#L59>

**Data First**

```ts
toCamelCase(data)
toCamelCase(data, { preserveConsecutiveUppercase })
```

**Parameters**

- `data`: A string.
- `options` (optional): An _optional_ object with the _optional_ property
`preserveConsecutiveUppercase` that can be used to change the way consecutive
uppercase characters are handled. Defaults to `true`.

**Returns** `Object`

**Example**

```ts
toCamelCase('hello world'); // "helloWorld"
toCamelCase('__HELLO_WORLD__'); // "helloWorld"
toCamelCase('HasHTML'); // "hasHTML"
toCamelCase('HasHTML', { preserveConsecutiveUppercase: false }); // "hasHtml"
```

**Data Last**

```ts
toCamelCase()(data)
toCamelCase({ preserveConsecutiveUppercase })(data)
```

**Parameters**

- `options` (optional): An _optional_ object with the _optional_ property
`preserveConsecutiveUppercase` that can be used to change the way consecutive
uppercase characters are handled. Defaults to `true`.

**Returns** `Function`

**Example**

```ts
pipe('hello world', toCamelCase()); // "helloWorld"
pipe('__HELLO_WORLD__', toCamelCase()); // "helloWorld"
pipe('HasHTML', toCamelCase()); // "hasHTML"
pipe('HasHTML', toCamelCase({ preserveConsecutiveUppercase: false })); // "hasHtml"
```

### toKebabCase

Converts text to **kebab-case** by splitting it into words and joining them
back together with hyphens (`-`), then lowercasing the result.

Because it uses [`toLowerCase`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLowerCase),
the function shares its _[locale inaccuracies](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLocaleLowerCase#description)_
too, making it best suited for simple strings like identifiers and internal
keys. For linguistic text processing, use [`Intl.Segmenter`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter)
with [`granularity: "word"`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter#parameters), and
[`toLocaleLowerCase`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLocaleLowerCase),
which are purpose-built to handle nuances in languages and locales.

For other case manipulations see: [`toLowerCase`](#toLowerCase), [`toUpperCase`](#toUpperCase), [`capitalize`](#capitalize),
[`uncapitalize`](#uncapitalize), [`toCamelCase`](#toCamelCase), [`toSnakeCase`](#toSnakeCase), and [`toTitleCase`](#toTitleCase).

For *COBOL-CASE* use `toUpperCase(toKebabCase(data))`.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/to-kebab-case.ts#L35>

**Data First**

```ts
toKebabCase(data)
```

**Parameters**

- `data`: A string.

**Returns** `Object`

**Example**

```ts
toKebabCase('hello world'); // "hello-world"
toKebabCase('__HELLO_WORLD__'); // "hello-world"
```

**Data Last**

```ts
toKebabCase()(data)
```

**Returns** `Function`

**Example**

```ts
pipe('hello world', toKebabCase()); // "hello-world"
pipe('__HELLO_WORLD__', toKebabCase()); // "hello-world"
```

### toLowerCase

Replaces all uppercase characters with their lowercase equivalents.

This function is a wrapper around the built-in
[`String.prototype.toLowerCase`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLowerCase)
method and shares its _[locale inaccuracies](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLocaleLowerCase#description)_.

For a more linguistically accurate transformation use [`toLocaleLowerCase`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLocaleLowerCase),
and for display purposes use CSS [`text-transform: lowercase;`](https://developer.mozilla.org/en-US/docs/Web/CSS/text-transform)
which *is* locale-aware.

For other case manipulations see: [`toUpperCase`](#toUpperCase), [`capitalize`](#capitalize),
[`uncapitalize`](#uncapitalize), [`toCamelCase`](#toCamelCase), [`toKebabCase`](#toKebabCase), [`toSnakeCase`](#toSnakeCase), and
[`toTitleCase`](#toTitleCase).

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/to-lower-case.ts#L26>

**Data First**

```ts
toLowerCase(data)
```

**Parameters**

- `data`: A string.

**Returns** `Object`

**Example**

```ts
toLowerCase('Hello World'); // "hello world"
```

**Data Last**

```ts
toLowerCase()(data)
```

**Returns** `Function`

**Example**

```ts
pipe('Hello World', toLowerCase()); // "hello world"
```

### toSnakeCase

Converts text to **snake_case** by splitting it into words and joining them
back together with underscores (`_`), then lowercasing the result.

Because it uses [`toLowerCase`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLowerCase),
the function shares its _[locale inaccuracies](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLocaleLowerCase#description)_
too, making it best suited for simple strings like identifiers and internal
keys. For linguistic text processing, use [`Intl.Segmenter`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter)
with [`granularity: "word"`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter#parameters), and
[`toLocaleLowerCase`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLocaleLowerCase),
which are purpose-built to handle nuances in languages and locales.

For other case manipulations see: [`toLowerCase`](#toLowerCase), [`toUpperCase`](#toUpperCase), [`capitalize`](#capitalize),
[`uncapitalize`](#uncapitalize), [`toCamelCase`](#toCamelCase), [`toKebabCase`](#toKebabCase), and [`toTitleCase`](#toTitleCase).

For *CONSTANT_CASE* use `toUpperCase(toSnakeCase(data))`.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/to-snake-case.ts#L35>

**Data First**

```ts
toSnakeCase(data)
```

**Parameters**

- `data`: A string.

**Returns** `Object`

**Example**

```ts
toSnakeCase('hello world'); // "hello_world"
toSnakeCase('__HELLO_WORLD__'); // "hello_world"
```

**Data Last**

```ts
toSnakeCase()(data)
```

**Returns** `Function`

**Example**

```ts
pipe('hello world', toSnakeCase()); // "hello_world"
pipe('__HELLO_WORLD__', toSnakeCase()); // "hello_world"
```

### toTitleCase

Converts text to **Title Case** by splitting it into words, capitalizing the
first letter of each word, then joining them back together with spaces.

Because it uses the built-in case conversion methods, the function shares
their _[locale inaccuracies](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLocaleLowerCase#description)_,
making it best suited for simple strings like identifiers and internal keys.
For linguistic text processing, use [`Intl.Segmenter`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter)
with [`granularity: "word"`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter#parameters),
[`toLocaleLowerCase`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLocaleLowerCase),
and [`toLocaleUpperCase`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLocaleUpperCase)
which are purpose-built to handle nuances in languages and locales.

For other case manipulations see: [`toLowerCase`](#toLowerCase), [`toUpperCase`](#toUpperCase), [`capitalize`](#capitalize),
[`uncapitalize`](#uncapitalize), [`toCamelCase`](#toCamelCase), [`toKebabCase`](#toKebabCase), and [`toSnakeCase`](#toSnakeCase).

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/to-title-case.ts#L78>

**Data First**

```ts
toTitleCase(data)
toTitleCase(data, { preserveConsecutiveUppercase })
```

**Parameters**

- `data`: A string.
- `options` (optional): An _optional_ object with the _optional_ property
`preserveConsecutiveUppercase` that can be used to change the way consecutive
uppercase characters are handled. Defaults to `true`.

**Returns** `Object`

**Example**

```ts
toTitleCase('hello world'); // "Hello World"
toTitleCase('--foo-bar--'); // "Foo Bar"
toTitleCase('fooBar'); // "Foo Bar"
toTitleCase('__FOO_BAR__'); // "Foo Bar"
toTitleCase('XMLHttpRequest'); // "XML Http Request"
toTitleCase('XMLHttpRequest', { preserveConsecutiveUppercase: false }); // "Xml Http Request"
```

**Data Last**

```ts
toTitleCase()(data)
toTitleCase({ preserveConsecutiveUppercase })(data)
```

**Parameters**

- `options` (optional): An _optional_ object with the _optional_ property
`preserveConsecutiveUppercase` that can be used to change the way consecutive
uppercase characters are handled. Defaults to `true`.

**Returns** `Function`

**Example**

```ts
pipe('hello world', toTitleCase()); // "Hello World"
pipe('--foo-bar--', toTitleCase()); // "Foo Bar"
pipe('fooBar', toTitleCase()); // "Foo Bar"
pipe('__FOO_BAR__', toTitleCase()); // "Foo Bar"
pipe('XMLHttpRequest', toTitleCase()); // "XML Http Request"
pipe('XMLHttpRequest', toTitleCase({ preserveConsecutiveUppercase: false })); // "Xml Http Request"
```

### toUpperCase

Replaces all lowercase characters with their uppercase equivalents.

This function is a wrapper around the built-in
[`String.prototype.toUpperCase`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase)
method and shares its _[locale inaccuracies](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLocaleUpperCase#description)_.

For a more linguistically accurate transformation use [`toLocaleUpperCase`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLocaleUpperCase),
and for display purposes use CSS [`text-transform: uppercase;`](https://developer.mozilla.org/en-US/docs/Web/CSS/text-transform)
which *is* locale-aware.

For other case manipulations see: [`toLowerCase`](#toLowerCase), [`capitalize`](#capitalize),
[`uncapitalize`](#uncapitalize), [`toCamelCase`](#toCamelCase), [`toKebabCase`](#toKebabCase), [`toSnakeCase`](#toSnakeCase), and
[`toTitleCase`](#toTitleCase).

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/to-upper-case.ts#L26>

**Data First**

```ts
toUpperCase(data)
```

**Parameters**

- `data`: A string.

**Returns** `Object`

**Example**

```ts
toUpperCase('Hello World'); // "HELLO WORLD"
```

**Data Last**

```ts
toUpperCase()(data)
```

**Returns** `Function`

**Example**

```ts
pipe('Hello World', toUpperCase()); // "HELLO WORLD"
```

### truncate

Truncates strings to a maximum length, adding an ellipsis when truncated.

Shorter strings are returned unchanged. If the omission marker is longer than
the maximum length, it will be truncated as well.

The `separator` argument provides more control by optimistically searching
for a matching cutoff point, which could be used to avoid truncating in the
middle of a word or other semantic boundary.

If you just need to limit the total length of the string, without adding an
`omission` or optimizing the cutoff point via `separator`, prefer
[`sliceString`](#sliceString) instead, which runs more efficiently.

The function counts Unicode characters, not visual graphemes, and may split
emojis, denormalized diacritics, or combining characters, in the middle. For
display purposes, prefer CSS [`text-overflow: ellipsis`](https://developer.mozilla.org/en-US/docs/Web/CSS/text-overflow#ellipsis)
which is locale-aware and purpose-built for this task.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/truncate.ts#L151>

**Data First**

```ts
truncate(data, n, { omission, separator })
```

**Parameters**

- `data`: The input string.
- `n`: The maximum length of the output string. The output will **never**
exceed this length.
- `options` (optional): An optional options object.

**Returns** `Object`

**Example**

```ts
truncate('Hello, world!', 8); //=> "Hello..."
truncate('cat, dog, mouse', 12, { omission: '__', separator: ',' }); //=> "cat, dog__"
```

**Data Last**

```ts
truncate(n, { omission, separator })(data)
```

**Parameters**

- `n`: The maximum length of the output string. The output will **never**
exceed this length.
- `options` (optional): An optional options object.

**Returns** `Function`

**Example**

```ts
pipe('Hello, world!' as const, truncate(8)); //=> "Hello..."
pipe(
  'cat, dog, mouse' as const,
  truncate(12, { omission: '__', separator: ',' }),
); //=> "cat, dog__"
```

### uncapitalize

Makes the first character of a string lowercase while leaving the rest
unchanged.

It uses the built-in [`String.prototype.toLowerCase`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLowerCase)
for the runtime and the built-in [`Uncapitalize`](https://www.typescriptlang.org/docs/handbook/2/template-literal-types.html#Uncapitalizestringtype)
utility type for typing and thus shares their _[locale inaccuracies](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLocaleLowerCase#description)_.

For display purposes, prefer using the CSS pseudo-element [`::first-letter`](https://developer.mozilla.org/en-US/docs/Web/CSS/::first-letter) to target
just the first letter of the word, and [`text-transform: lowercase`](https://developer.mozilla.org/en-US/docs/Web/CSS/text-transform#lowercase)
to lowercase it. This transformation **is** locale-aware.

For other case manipulations see: [`toUpperCase`](#toUpperCase), [`toLowerCase`](#toLowerCase), [`capitalize`](#capitalize),
[`toCamelCase`](#toCamelCase), [`toKebabCase`](#toKebabCase), [`toSnakeCase`](#toSnakeCase), and [`toTitleCase`](#toTitleCase).

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/uncapitalize.ts#L26>

**Data First**

```ts
uncapitalize(data)
```

**Parameters**

- `data`: A string.

**Returns** `Object`

**Example**

```ts
uncapitalize('HELLO WORLD'); // "hELLO WORLD"
```

**Data Last**

```ts
uncapitalize()(data)
```

**Returns** `Function`

**Example**

```ts
pipe('HELLO WORLD', uncapitalize()); // "hELLO WORLD"
```

## Utility

### stringToPath

A utility to allow JSONPath-like strings to be used in other utilities which
take an array of path segments as input (e.g. [`prop`](#prop), [`setPath`](#setPath), etc...).
The main purpose of this utility is to act as a bridge between the runtime
implementation that converts the path to an array, and the type-system that
parses the path string **type** into an array **type**. This type allows us
to return fine-grained types and to enforce correctness at the type-level.

We **discourage** using this utility for new code. This utility is for legacy
code that already contains path strings (which are accepted by Lodash). We
strongly recommend using *path arrays* instead as they provide better
developer experience via significantly faster type-checking, fine-grained
error messages, and automatic typeahead suggestions for each segment of the
path.

There are a bunch of limitations to this utility derived from the
limitations of the type itself, these are usually edge-cases around deeply
nested paths, escaping, whitespaces, and empty segments. This is true even
in cases where the runtime implementation can better handle them, this is
intentional. See the tests for this utility for more details and the
expected outputs*.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/string-to-path.ts#L90>

**Data First**

```ts
stringToPath(path)
```

**Parameters**

- `path`: A string path.

**Returns** `Object`

**Example**

```ts
stringToPath('a.b[0].c'); // => ['a', 'b', 0, 'c']
```

## Other

### DeepPartial (type)

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/type.helpers.ts#L1>

```ts
type DeepPartial<T> = T extends object
  ? { [P in keyof T]?: DeepPartial<T[P]> }
  : T;
```

### defaultTo

A stricter wrapper around the [Nullish coalescing operator `??`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator)
that ensures that the fallback matches the type of the data. Only works
when data can be `null` or `undefined`.

Notice that `Number.NaN` is not nullish and would not result in returning the
fallback!

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/default-to.ts#L34>

**Data First**

```ts
defaultTo(data, fallback)
```

**Parameters**

- `data`: A nullish value.
- `fallback`: A value of the same type as `data` that would be returned
when `data` is nullish.

**Returns** `Object`

**Example**

```ts
defaultTo('hello' as string | undefined, 'world'); //=> "hello"
defaultTo(undefined as string | undefined, 'world'); //=> "world"
```

**Data Last**

```ts
defaultTo(fallback)(data)
```

**Parameters**

- `fallback`: A value of the same type as `data` that would be returned
when `data` is nullish.

**Returns** `Function`

**Example**

```ts
pipe('hello' as string | undefined, defaultTo('world')); //=> "hello"
pipe(undefined as string | undefined, defaultTo('world')); //=> "world"
```

### isBrowser (constant)

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/index.ts#L170>

```ts
declare const isBrowser: boolean;
```

### KEY_CODES (constant)

Using event.code is not predictable since each machine may have different output

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/key-codes.ts#L5>

```ts
declare const KEY_CODES: {
  readonly ALT: 'Alt';
  readonly ARROW_DOWN: 'ArrowDown';
  readonly ARROW_LEFT: 'ArrowLeft';
  readonly ARROW_RIGHT: 'ArrowRight';
  readonly ARROW_UP: 'ArrowUp';
  readonly AT: '@';
  readonly BACKSPACE: 'Backspace';
  readonly CTRL: 'Control';
  readonly DELETE: 'Delete';
  readonly END: 'End';
  readonly ENTER: 'Enter';
  readonly ESC: 'Escape';
  readonly HOME: 'Home';
  readonly KEY_F: 'KEY_F';
  readonly META: 'Meta';
  readonly PAGE_DOWN: 'PageDown';
  readonly PAGE_UP: 'PageUp';
  readonly SHIFT: 'Shift';
  readonly SPACE: 'Space';
  readonly TAB: 'Tab';
};
```

### tap

Calls the given function with the given value, then returns the given value.
The return value of the provided function is ignored.

This allows "tapping into" a function sequence in a pipe, to perform side
effects on intermediate results.

Source: <https://github.com/vinicunca/perkakas/blob/v1.19.1/src/tap.ts#L19>

**Data First**

```ts
tap(value, fn)
```

**Parameters**

- `value`: The value to pass into the function.
- `fn`: The function to call.

**Returns** `Object`

**Example**

```ts
tap('foo', console.log); // => "foo"
```

**Data Last**

```ts
tap(fn)(value)
```

**Parameters**

- `fn`: The function to call.

**Returns** `Function`

**Example**

```ts
pipe(
  [-5, -1, 2, 3],
  filter((n) => n > 0),
  tap(console.log), // prints [2, 3]
  map((n) => n * 2),
); // => [4, 6]
```


---

- [GitHub](https://github.com/vinicunca/perkakas)
- [npm](https://www.npmjs.com/package/@vinicunca/perkakas)


## Sitemap

See the full [sitemap](https://vinicunca.dev/sitemap.md) for all pages.
