npm package: @pfeiferio/array-utils
Description: Small, dependency-free array utility functions for JavaScript and TypeScript
Author: Pascal Pfeifer
Latest version: 1.0.0

# @pfeiferio/array-utils

> Small, dependency-free array utility functions for JavaScript and TypeScript.

[![npm version](https://badge.fury.io/js/%40pfeiferio%2Farray-utils.svg)](https://www.npmjs.com/package/@pfeiferio/array-utils)
[![TypeScript](https://img.shields.io/badge/TypeScript-5.0-blue.svg)](https://www.typescriptlang.org/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Node.js](https://img.shields.io/badge/node-%3E%3D18-brightgreen.svg)](https://nodejs.org/)
[![codecov](https://codecov.io/gh/pfeiferio/array-utils/branch/main/graph/badge.svg)](https://codecov.io/gh/pfeiferio/array-utils)

## Installation

```bash
npm install @pfeiferio/array-utils
```

---

## Usage

```ts
import {
  arrayFirst,
  arrayLast,
  arrayUnique,
  arraySum
} from '@pfeiferio/array-utils'

const numbers = [1, 2, 3, 3]

arrayFirst(numbers)   // 1
arrayLast(numbers)    // 3
arrayUnique(numbers)  // [1, 2, 3]
arraySum(numbers)     // 9
```

Functions do not mutate the original array unless explicitly documented.

---

## API

### `arrayFirst(array, fallback?)`

Returns the first element of an array. Returns `fallback` (or `undefined`) if the array is empty.

```ts
arrayFirst([1, 2, 3])     // 1
arrayFirst([], 0)         // 0
arrayFirst([])            // undefined
```

---

### `arrayLast(array, fallback?)`

Returns the last element of an array. Returns `fallback` (or `undefined`) if the array is empty.

```ts
arrayLast([1, 2, 3])      // 3
arrayLast([], 0)          // 0
arrayLast([])             // undefined
```

---

### `arrayUnique(array)`

Returns a new array with duplicate values removed. Preserves insertion order. Objects are compared by reference.

```ts
arrayUnique([1, 2, 2, 3]) // [1, 2, 3]
```

---

### `arraySum(array)`

Sums all numeric values. Returns `0` for an empty array.

```ts
arraySum([1, 2, 3]) // 6
arraySum([])        // 0
```

---

### `arrayShuffle(array)`

Returns a new shuffled copy of the array using the Fisher-Yates algorithm. Does not mutate the original.

```ts
arrayShuffle([1, 2, 3, 4, 5]) // e.g. [3, 1, 5, 2, 4]
```

---

### `arraySort(array, sortOrder?)`

Sorts the array in place and returns it. Strings are sorted with `localeCompare`. `null` and `undefined` are always pushed to the end regardless of sort direction.

```ts
arraySort([3, 1, 2])                       // [1, 2, 3]
arraySort([3, 1, 2], 'descending')         // [3, 2, 1]
arraySort([3, 1, 2], arraySort.DESC)       // [3, 2, 1]
arraySort(['banana', 'apple'], 'ascending') // ['apple', 'banana']
arraySort([1, null, 2])                    // [1, 2, null]
```

> ⚠️ This function mutates the original array. Use `[...array]` to sort a copy.

---

### `arrayIntersect(arrayA, arrayB)`

Returns a new array with elements present in both arrays. Order follows `arrayA`.

```ts
arrayIntersect([1, 2, 3], [2, 3, 4]) // [2, 3]
```

---

### `arrayDifference(arrayA, arrayB)`

Returns a new array with elements from `arrayA` that are not in `arrayB`.

```ts
arrayDifference([1, 2, 3], [2]) // [1, 3]
```

---

### `arrayChunk(array, chunkSize)`

Splits an array into chunks of the given size. The last chunk may be smaller.

Throws a `RangeError` if `chunkSize` is not a positive integer.

```ts
arrayChunk([1, 2, 3, 4], 2) // [[1, 2], [3, 4]]
arrayChunk([1, 2, 3], 2)    // [[1, 2], [3]]
```

---

### `arrayCompact(array)`

Returns a new array with all falsy values removed (`false`, `null`, `undefined`, `0`, `""`, `NaN`).

```ts
arrayCompact([0, 1, false, 2, '', 3]) // [1, 2, 3]
```

---

### `arrayFlatten(array, depth?)`

Flattens nested arrays up to the given depth (default: `1`). Use `Infinity` to flatten completely.

Throws a `RangeError` if `depth` is not a positive integer or `Infinity`.

```ts
arrayFlatten([1, [2, [3]]])          // [1, 2, [3]]
arrayFlatten([1, [2, [3]]], 2)       // [1, 2, 3]
arrayFlatten([1, [2, [3]]], Infinity) // [1, 2, 3]
```

---

### `objectToArray(object)`

Converts an object with non-negative integer string keys into an array. Non-numeric, float, or negative keys are ignored. Gaps between keys result in `undefined` slots.

Throws a `RangeError` if any key exceeds `100_000`.

```ts
objectToArray({ '0': 'a', '1': 'b', '2': 'c' }) // ['a', 'b', 'c']
objectToArray({ '0': 'a', '2': 'c' })            // ['a', undefined, 'c']
objectToArray({ '1.5': 'a', '0': 'b' })          // ['b']  (float key ignored)
```

---

### `isArray(value)`

Type guard that returns true if value is an array.

```ts
isArray([1, 2, 3]) // true
isArray([])        // true
isArray(null)      // false
```

---

### `assertArray(value, message?)`

Assertion function that throws a `TypeError` if `value` is not an array. Narrows the type to `T[]` after a successful call.

```ts
assertArray(value)                          // throws if not an array
assertArray(value, 'tags must be an array') // custom error message
```

---

## Design Goals

* No dependencies
* Fully typed (TypeScript)
* Tree-shakable
* Functional approach (no prototype extensions)
* Small surface area

---

## License

MIT