@js-fns/array
v0.1.0
Published
Tiny JS array utilities
Readme
@js-fns/array
Tiny type-safe JS array utilities collection.
It features dual CJS/ESM support and built-in TypeScript definitions.
Installation
The package is available as a standalone npm package:
npm install @js-fns/arrayIt is also available as a part of the js-fns collection:
npm install js-fnsAPI
@js-fns/array provides the following utilities:
last— Returns the last array element.sample— Returns a random array element.uniq— Removes duplicate array elements.
last
The last function returns the final array element, or undefined when the array is empty. For tuples, it preserves the final element's type:
import { last } from "@js-fns/array";
last([1, 2, 3]);
//=> 3
last([]);
//=> undefined
const status = last(["pending", "done"] as const);
//=> "done"
status satisfies "done";sample
The sample function returns a random array element, or undefined when the array is empty. Known nonempty tuples exclude undefined from the return type:
import { sample } from "@js-fns/array";
sample([1, 2, 3]);
//=> 1 or 2 or 3
const coin = sample(["heads", "tails"] as const);
//=> "heads" or "tails"
coin satisfies "heads" | "tails";uniq
The uniq function returns a new array of unique elements in first-occurrence order. It compares objects by reference, treats repeated NaN values as equal, and normalizes -0 to 0. Empty, omitted, or nullish inputs return an empty array:
import { uniq } from "@js-fns/array";
uniq([1, 2, 1, 3, 2]);
//=> [1, 2, 3]
uniq([NaN, NaN, -0, 0]);
//=> [NaN, 0]t.Array
@js-fns/array expose TypeScript type utilities under the shared t namespace.
It is implemented through virtual package @js-fns/types that consolidates all type utilities contributed by individual js-fns packages into a single namespace.
See t Namespace & Virtual Package for setup and usage details.
t.Array.Last
The t.Array.Last type infers the type of the last element in a tuple or element type or undefined for regular arrays.
import type { t } from "@js-fns/types";
type TupleLast = t.Array.Last<[1, 2, 3]>;
//=> 3
type ArrayLast = t.Array.Last<Array<number>[]>;
//=> number | undefinedChangelog
See the changelog.
