Utilities for predicates, identity transforms, and asynchronous callbacks.
These dependency-free utilities work in current browsers, Node, Deno, and Bun.
import fn from "@rcompat/fn";fn.defined#
Checks that a value is not undefined and narrows its type.
Type parameters
T— Input value type.
Parameters
value— Value to inspect.
fn.defined<T>(value: T): value is Exclude<T, undefined>;fn.identity#
Returns a value unchanged while preserving its type and identity.
Type parameters
T— Input value type.
Parameters
value— Value to return.
fn.identity<T>(value: T): T;fn.async#
Concurrent asynchronous collection operations.
fn.async: AsyncUtilities;Async methods#
fn.async.map()#
Maps all array elements concurrently and preserves their result order.
Without options, the mapper is invoked through Array.map and all returned
promises are awaited together with Promise.all. A concurrency limit
bounds simultaneously running callbacks. Results always retain input
order.
Rejection or cancellation stops new callbacks from starting. Cancellation rejects promptly, but callbacks already running must observe the supplied signal themselves if they need to stop their own work.
concurrency, when supplied, must be a finite positive integer. Empty
arrays resolve to [], except that an already-aborted signal rejects
before any callback starts.
Type parameters
T— Input element type.U— Resolved output element type.
Parameters
array— Array to map.mapper— Asynchronous mapping callback.options— Concurrency and cancellation controls.
Returns: A promise for mapped results in input order.
Throws: A RangeError when concurrency is invalid, or the signal's
reason when cancellation occurs.
fn.async.map<T, U>(
array: T[],
mapper: AsyncMapper<T, U>,
options?: AsyncMapOptions,
): Promise<U[]>;Example
await fn.async.map([1, 2], async value => value * 2); // [2, 4]Supporting contracts#
AsyncUtilities#
Concurrent asynchronous collection operations.
interface AsyncUtilities {
// Maps all array elements concurrently and preserves their result order.
map<T, U>(
array: T[],
mapper: AsyncMapper<T, U>,
options?: AsyncMapOptions,
): Promise<U[]>;
}AsyncMapper#
Callback used by fn.async.map.
Type parameters
T— Input element type.U— Resolved output element type.
Parameters
value— Current array element.index— Current zero-based index.array— Array being mapped.
Returns: A promise for the mapped value.
interface AsyncMapper<T, U> {
(value: T, index: number, array: T[]): Promise<U>;
}AsyncMapOptions#
Options for fn.async.map.
interface AsyncMapOptions {
// Maximum number of mapper callbacks running at once.
concurrency?: number;
// Cancels scheduling and rejects the map operation.
signal?: AbortSignal;
}