radashi
Version:
The modern, community-first TypeScript toolkit with all of the fast, readable, and minimal utility functions you need. Type-safe, dependency-free, tree-shakeable, fully tested.
1,270 lines (1,225 loc) • 145 kB
text/typescript
/**
* Sort an array without modifying it and return the newly sorted
* value. Allows for a string sorting value.
*
* @see https://radashi.js.org/reference/array/alphabetical
* @version 12.1.0
*/
declare function alphabetical<T>(array: readonly T[], getter: (item: T) => string, direction?: 'asc' | 'desc'): T[];
/**
* Go through a list of items, starting with the first item, and
* comparing with the second. Keep the one you want then compare that
* to the next item in the list with the same.
*
* @see https://radashi.js.org/reference/array/boil
* @example
* ```ts
* boil([1, 2, 3, 0], (a, b) => a > b ? a : b) // 3
* ```
* @version 12.1.0
*/
declare function boil<T>(array: readonly T[], compareFunc: (a: T, b: T) => T): T | null;
type ReadonlyArray2D<T> = readonly (readonly T[])[];
/**
* Create an [n-ary Cartesian product](https://en.wikipedia.org/wiki/Cartesian_product#n-ary_Cartesian_product)
* from the given arrays.
*
* @see https://radashi.js.org/reference/array/cartesianProduct
* @example
* ```ts
* cartesianProduct([
* ['red', 'blue'],
* ['big', 'small'],
* ['fast', 'slow'],
* ])
* // [
* // ['red', 'big', 'fast'],
* // ['red', 'big', 'slow'],
* // ['red', 'small', 'fast'],
* // ['red', 'small', 'slow'],
* // ['blue', 'big', 'fast'],
* // ['blue', 'big', 'slow'],
* // ['blue', 'small', 'fast'],
* // ['blue', 'small', 'slow']
* // ]
* ```
* @version 12.3.0
*/
declare function cartesianProduct<const T extends ReadonlyArray2D<any>>(...arrays: [...T]): Array<{
[K in keyof T]: T[K][number];
}>;
/**
* Casts the given value to an array. If the value is already an
* array, a shallow copy is returned. Otherwise, a new array
* containing the value is returned.
*
* @see https://radashi.js.org/reference/array/castArray
* @example
* ```ts
* castArray(1) // => [1]
* castArray([1, 2]) // => [1, 2]
* castArray(null) // => [null]
* castArray(undefined) // => [undefined]
* ```
* @version 12.2.0
*/
declare function castArray<T>(value: T): CastArray<T>;
/**
* The return type of the {@link castArray} function.
*
* @see https://radashi.js.org/reference/array/castArray
*/
type CastArray<T> = [T] extends [never] ? never[] : [unknown] extends [T] ? unknown[] : (T extends any ? T extends readonly (infer U)[] ? U[] : never : never) | (Exclude<T, readonly any[]> extends never ? never : Exclude<T, readonly any[]>[]);
/**
* Casts the given value to an array if it's not equal to `null` or
* `undefined`. If the value is an array, it returns a shallow copy of
* the array. Otherwise, it returns a new array containing the value.
*
* @see https://radashi.js.org/reference/array/castArrayIfExists
* @example
* ```ts
* castArrayIfExists(1) // => [1]
* castArrayIfExists(null) // => null
* castArrayIfExists(undefined) // => undefined
* castArrayIfExists([1, 2, 3]) // => [1, 2, 3]
* ```
* @version 12.2.0
*/
declare function castArrayIfExists<T>(value: T): CastArrayIfExists<T>;
/**
* The return type of the {@link castArrayIfExists} function.
*
* @see https://radashi.js.org/reference/array/castArrayIfExists
*/
type CastArrayIfExists<T> = [T] extends [never] ? never[] : [unknown] extends [T] ? unknown[] | null | undefined : (T extends any ? T extends readonly (infer U)[] ? U[] : never : never) | (Exclude<T, readonly any[] | null | undefined> extends never ? never : Exclude<T, readonly any[] | null | undefined>[]) | Extract<T, null | undefined>;
/**
* Splits a single list into many lists of the desired size.
*
* @see https://radashi.js.org/reference/array/cluster
* @example
* ```ts
* cluster([1, 2, 3, 4, 5, 6], 2)
* // [[1, 2], [3, 4], [5, 6]]
* ```
* @version 12.1.0
*/
declare function cluster<T, Size extends number = 2>(array: readonly T[], size?: Size): Cluster<T, Size>[];
type Cluster<T, Size extends number> = Size extends 1 ? [T] : Size extends 2 ? [T, T] : Size extends 3 ? [T, T, T] : Size extends 4 ? [T, T, T, T] : Size extends 5 ? [T, T, T, T, T] : Size extends 6 ? [T, T, T, T, T, T] : Size extends 7 ? [T, T, T, T, T, T, T] : Size extends 8 ? [T, T, T, T, T, T, T, T] : T[];
type Concat<T extends readonly any[]> = T[number] extends infer TElement ? (TElement extends readonly (infer TNestedElement)[] ? Exclude<TNestedElement, undefined | null> : Exclude<TElement, undefined | null>)[] : unknown[];
/**
* Flattens and filters nullish values from arguments, returning a new
* array containing only the non-nullish elements. Nested arrays are
* flattened one level deep.
*
* @see https://radashi.js.org/reference/array/concat
* @example
* ```ts
* const result = _.concat('', ['a'], undefined, [null, 'b'])
* // => ['', 'a', 'b']
* ```
* @example
* ```ts
* const result = _.concat(1, [2, [3]], null)
* // => [1, 2, [3]] // Note: only flattens one level
* ```
* @version 12.5.0
*/
declare function concat<T extends readonly [any, any, ...any[]]>(...values: T): Concat<T>;
/**
* Counts the occurrences of each unique value returned by the `identity`
* function when applied to each item in the array.
*
* @see https://radashi.js.org/reference/array/counting
* @example
* ```ts
* counting([1, 2, 3, 4], (n) => n % 2 === 0 ? 'even' : 'odd')
* // { even: 2, odd: 2 }
* ```
* @version 12.1.0
*/
declare function counting<T, TId extends string | number | symbol>(array: readonly T[], identity: (item: T) => TId): Record<TId, number>;
/**
* Returns all items from the first list that do not exist in the
* second list.
*
* @see https://radashi.js.org/reference/array/diff
* @example
* ```ts
* diff([1, 2, 3, 4], [2, 4])
* // [1, 3]
*
* diff([{a:1}, {a:2}, {a:3}], [{a:2}, {a:4}], (n) => n.a)
* // [{a:1}, {a:3}]
* ```
* @version 12.1.0
*/
declare function diff<T>(root: readonly T[], other: readonly T[], identity?: (item: T) => string | number | symbol): T[];
/**
* Get the first item in an array or a default value.
*
* @see https://radashi.js.org/reference/array/first
* @example
* ```ts
* first([1, 2, 3, 4])
* // 1
*
* first([], 0)
* // 0
* ```
* @version 12.1.0
*/
declare function first<const TArray extends readonly any[], const TDefault = undefined>(array: TArray, defaultValue?: TDefault): TArray extends readonly [infer TFirst, ...any[]] ? TFirst : TArray[number] | TDefault;
/**
* Given an array of arrays, returns a single dimensional array with
* all items in it.
*
* @see https://radashi.js.org/reference/array/flat
* @example
* ```ts
* flat([[1, 2], [[3], 4], [5]])
* // [1, 2, [3], 4, 5]
* ```
* @version 12.1.0
*/
declare function flat<T>(lists: readonly T[][]): T[];
/**
* Split an array into two array based on a true/false condition
* function.
*
* @see https://radashi.js.org/reference/array/fork
* @example
* ```ts
* fork([1, 2, 3, 4], (n) => n % 2 === 0)
* // [[2, 4], [1, 3]]
* ```
* @version 12.1.0
*/
declare function fork<T>(array: readonly T[], condition: (item: T) => boolean): [T[], T[]];
/**
* Sorts an `array` of items into groups. The return value is a map
* where the keys are the group IDs the given `getGroupId` function
* produced and the value is an array of each item in that group.
*
* @see https://radashi.js.org/reference/array/group
* @example
* ```ts
* group([1, 2, 3, 4], (n) => n % 2 === 0 ? 'even' : 'odd')
* // { even: [2], odd: [1, 3, 4] }
* ```
* @version 12.1.0
*/
declare function group<T, Key extends string | number | symbol>(array: readonly T[], getGroupId: (item: T) => Key): {
[K in Key]?: T[];
};
/**
* Given two arrays, returns true if any elements intersect.
*
* @see https://radashi.js.org/reference/array/intersects
* @example
* ```ts
* intersects([1, 2, 3], [4, 5, 6])
* // false
*
* intersects([1, 0, 0], [0, 1], (n) => n > 1)
* // true
* ```
* @version 12.1.0
*/
declare function intersects<T, K>(listA: readonly T[], listB: readonly T[], identity?: (t: T) => K): boolean;
/**
* Like a reduce but does not require an array. Only need a number and
* will iterate the function as many times as specified.
*
* NOTE: This is NOT zero indexed. If you pass count=5 you will get 1,
* 2, 3, 4, 5 iteration in the callback function.
*
* @see https://radashi.js.org/reference/array/iterate
* @example
* ```ts
* iterate(3, (total, i) => total + i, 0)
* // 6
* ```
* @version 12.1.0
*/
declare function iterate<T>(count: number, func: (currentValue: T, iteration: number) => T, initValue: T): T;
/**
* Get the last item in an array or a default value.
*
* @see https://radashi.js.org/reference/array/last
* @example
* ```ts
* last([1, 2, 3, 4])
* // 4
*
* last([], 0)
* // 0
* ```
* @version 12.1.0
*/
declare function last<const TArray extends readonly any[], const TDefault = undefined>(array: TArray, defaultValue?: TDefault): TArray extends readonly [...any[], infer TLast] ? TLast : TArray[number] | TDefault;
/**
* Creates a list of given start, end, value, and step parameters.
*
* @see https://radashi.js.org/reference/array/list
* @example
* ```ts
* list(3) // 0, 1, 2, 3
* list(0, 3) // 0, 1, 2, 3
* list(0, 3, 'y') // y, y, y, y
* list(0, 3, () => 'y') // y, y, y, y
* list(0, 3, i => i) // 0, 1, 2, 3
* list(0, 3, i => `y${i}`) // y0, y1, y2, y3
* list(0, 3, obj) // obj, obj, obj, obj
* list(0, 6, i => i, 2) // 0, 2, 4, 6
* ```
* @version 12.1.0
*/
declare function list<T = number>(startOrLength: number, end?: number, valueOrMapper?: T | ((i: number) => T), step?: number): T[];
/**
* Create a new `Map` instance from an array.
*
* @see https://radashi.js.org/reference/array/mapify
* @example
* ```ts
* const array = [
* { id: 1, name: 'Fred' },
* { id: 2, name: 'Annie' },
* ]
*
* mapify(
* array,
* item => item.id,
* item => item.name,
* )
* // Map(2) { 1 => 'Fred', 2 => 'Annie' }
* ```
* @version 12.2.0
*/
declare function mapify<T, Key, Value = T>(array: readonly T[], getKey: (item: T, index: number) => Key, getValue?: (item: T, index: number) => Value): Map<Key, Value>;
/**
* Given two arrays of the same type, iterate the first list and
* replace items matched by the `matcher` function in the first place.
* The given arrays are never modified.
*
* @see https://radashi.js.org/reference/array/merge
* @example
* ```ts
* merge(
* [{id: 1}, {id: 2}],
* [{id: 3}, {id: 1, name: 'John'}],
* (obj) => obj.id
* )
* // [{id: 1, name: 'John'}, {id: 2}]
* ```
* @version 12.1.0
*/
declare function merge<T>(prev: readonly T[], array: readonly T[], toKey: (item: T) => any): T[];
/**
* Convert an array to a dictionary by mapping each item into a
* dictionary key & value.
*
* @see https://radashi.js.org/reference/array/objectify
* @example
* ```ts
* objectify([1, 2, 3], (n) => '#' + n)
* // { '#1': 1, '#2': 2, '#3': 3 }
*
* objectify(
* [{id: 1, name: 'John'}, {id: 2, name: 'Jane'}],
* (obj) => obj.id,
* (obj) => obj.name
* )
* // { 1: 'John', 2: 'Jane' }
* ```
* @version 12.1.0
*/
declare function objectify<T, Key extends string | number | symbol, Value = T>(array: readonly T[], getKey: (item: T) => Key, getValue?: (item: T) => Value): Record<Key, Value>;
/**
* Extracts values from an array of objects based on specified
* mappings. Useful for extracting multiple properties from an array
* of objects (e.g. for tabular data). Also supports “computed
* properties” via mapping functions, which can combine and transform
* values on-the-fly.
*
* - If mappings are provided, returns an array of arrays where each
* inner array contains the values extracted by applying each
* mapping to the corresponding object.
* - If no mappings are provided, returns an array of arrays
* containing all values of each object.
*
* @see https://radashi.js.org/reference/array/pluck
* @example
* ```ts
* interface God {
* name: string;
* power: number;
* domain: string;
* }
*
* const gods: God[] = [
* { name: 'Ra', power: 100, domain: 'Sun' },
* { name: 'Zeus', power: 98, domain: 'Lightning' },
* { name: 'Loki', power: 72, domain: 'Tricks' }
* ];
*
* // Extract a set of properties
* pluck(gods, ['power', 'domain']);
* // [[100, 'Sun'], [98, 'Lightning'], [72, 'Tricks']]
*
* // Extract all properties
* pluck(gods);
* // [['Ra', 100, 'Sun'], ['Zeus', 98, 'Lightning'], ['Loki', 72, 'Tricks']]
* ```
* @version 12.5.0
*/
declare function pluck<T extends object, TMapping extends Mapping<T>>(array: readonly T[], mappings: readonly TMapping[]): MappedOutput<TMapping, T>[];
declare function pluck<T extends object>(array: readonly T[], mappings?: readonly Mapping<T>[]): unknown[];
/**
* Removes elements from an array based on the specified predicate
* function.
*
* @see https://radashi.js.org/reference/array/remove
* @example
* ```ts
* // Example 1: Remove even numbers from an array
* const numbers = [1, 2, 3, 4, 5];
* const result = remove(numbers, value => value % 2 === 0);
* console.log(result); // Output: [1, 3, 5]
*
* // Example 2: Remove objects with a specific property value
* const items = [
* { id: 1, active: true },
* { id: 2, active: false },
* { id: 3, active: true }
* ];
* const result = remove(items, item => item.active);
* console.log(result); // Output: [{ id: 2, active: false }]
* ```
* @version 12.4.0
*/
declare function remove<T>(array: readonly T[], predicate: (value: T) => boolean): T[];
/**
* Replace an element in an array with a new item without modifying
* the array and return the new value.
*
* @see https://radashi.js.org/reference/array/replace
* @example
* ```ts
* replace([1, 2, 3], 4, (n) => n === 2)
* // [1, 4, 3]
* ```
* @version 12.1.0
*/
declare function replace<T>(array: readonly T[], newItem: T, match: (item: T, idx: number) => boolean): T[];
/**
* Replace the first occurrence of an item in an array where the
* `match` function returns true. If no items match, append the new
* item to the end of the list.
*
* @see https://radashi.js.org/reference/array/replaceOrAppend
* @example
* ```ts
* replaceOrAppend([1, 2, 3], 4, (n) => n > 1)
* // [1, 4, 3]
*
* replaceOrAppend([1, 2, 3], 4, (n) => n > 100)
* // [1, 2, 3, 4]
* ```
* @version 12.1.0
*/
declare function replaceOrAppend<T>(array: readonly T[], newItem: T, match: (a: T, idx: number) => boolean): T[];
/**
* Select performs a filter and a mapper inside of a reduce, only
* iterating the list one time. If condition is omitted, will
* select all mapped values that are non-nullish.
*
* @see https://radashi.js.org/reference/array/select
* @example
* ```ts
* select(
* [1, 2, 3, 4],
* x => x * x,
* x => x > 2
* )
* // => [9, 16]
* ```
* @version 12.1.0
*/
declare function select<T, U>(array: readonly T[], mapper: (item: T, index: number) => U, condition: ((item: T, index: number) => boolean) | null | undefined): U[];
declare function select<T, U>(array: readonly T[], mapper: (item: T, index: number) => U | null | undefined): U[];
/**
* Select performs a find + map operation, short-circuiting on the first
* element that satisfies the prescribed condition. If condition is omitted,
* will select the first mapped value which is non-nullish.
*
* @see https://radashi.js.org/reference/array/selectFirst
* @example
* ```ts
* selectFirst(
* [1, 2, 3, 4],
* x => x * x,
* x => x > 2
* )
* // => 9
* ```
* @version 12.2.0
*/
declare function selectFirst<T, U>(array: readonly T[], mapper: (item: T, index: number) => U, condition?: (item: T, index: number) => boolean): U | undefined;
/**
* Shifts array items by `n` steps. If `n` is greater than 0, items
* will shift `n` steps to the right. If `n` is less than 0, items
* will shift `n` steps to the left.
*
* @see https://radashi.js.org/reference/array/shift
* @example
* ```ts
* shift([1, 2, 3], 1) // [3, 1, 2]
* shift([1, 2, 3], -1) // [2, 3, 1]
* ```
* @version 12.1.0
*/
declare function shift<T>(arr: readonly T[], n: number): T[];
/**
* Given a list returns a new list with only truthy values.
*
* @see https://radashi.js.org/reference/array/sift
* @example
* ```ts
* sift([0, 1, undefined, null, 2, false, 3, ''])
* // => [1, 2, 3]
* ```
* @version 12.1.0
*/
declare function sift<T>(array: readonly (T | Falsy)[]): T[];
/**
* Sort an array without modifying it and return the newly sorted
* value.
*
* @see https://radashi.js.org/reference/array/sort
* @example
* ```ts
* const fish = [
* { name: 'Marlin', weight: 105 },
* { name: 'Bass', weight: 8 },
* { name: 'Trout', weight: 13 }
* ]
*
* sort(fish, f => f.weight) // => [Bass, Trout, Marlin]
* sort(fish, f => f.weight, true) // => [Marlin, Trout, Bass]
* ```
* @version 12.1.0
*/
declare function sort<T>(array: readonly T[], getter: (item: T) => number, desc?: boolean): T[];
/**
* Either adds or removes an item from an array, based on whether it
* already exists in the array. If multiple items match the given
* `item`, all matching items will be removed.
*
* Note that the given `array` is *not mutated*. A copy of the array
* is returned with the given item either added or removed.
*
* - **"toKey" parameter**
* - You may define a `toKey` callback, which is a function that
* converts an item into a value that can be checked for equality.
* When called with the given `item`, an index of -1 will be passed.
*
* - **"strategy" option**
* - You may define a `strategy` option, which determines where the
* item should be added in the array.
*
* @see https://radashi.js.org/reference/array/toggle
* @example
* ```ts
* toggle([1, 2, 3], 4) // => [1, 2, 3, 4]
* toggle([1, 2, 3], 2) // => [1, 3]
*
* toggle(
* [
* { id: 1 },
* { id: 2 },
* ],
* { id: 3 },
* (obj) => obj.id,
* { strategy: 'prepend' }
* )
* // => [{ id: 3 }, { id: 1 }, { id: 2 }]
* ```
* @version 12.1.0
*/
declare function toggle<T>(array: readonly T[], item: T, toKey?: ((item: T, idx: number) => number | string | symbol) | null, options?: {
strategy?: 'prepend' | 'append';
}): T[];
/**
* Given a list of items returns a new list with only unique items.
* Accepts an optional identity function to convert each item in the
* list to a comparable identity value.
*
* @see https://radashi.js.org/reference/array/unique
* @example
* ```ts
* unique([1, 1, 2, 2]) // => [1, 2]
* unique([1, 2, 3], (n) => n % 2) // => [1, 2]
* ```
* @version 12.1.0
*/
declare function unique<T, K = T>(array: readonly T[], toKey?: (item: T) => K): T[];
/**
* Creates an array of ungrouped elements, where each resulting array
* contains all elements at a specific index from the input arrays.
* The first array contains all first elements, the second array
* contains all second elements, and so on.
*
* @see https://radashi.js.org/reference/array/unzip
* @example
* ```ts
* unzip([['a', 1, true], ['b', 2, false]])
* // [['a', 'b'], [1, 2], [true, false]]
* ```
* @version 12.2.0
*/
declare function unzip<T>(arrays: readonly (readonly T[])[]): T[][];
/**
* Creates an array of grouped elements, the first of which contains
* the first elements of the given arrays, the second of which
* contains the second elements of the given arrays, and so on.
*
* @see https://radashi.js.org/reference/array/zip
* @example
* ```ts
* zip(['a', 'b'], [1, 2], [true, false])
* // [['a', 1, true], ['b', 2, false]]
* ```
* @version 12.1.0
*/
declare function zip<T1, T2, T3, T4, T5>(array1: readonly T1[], array2: readonly T2[], array3: readonly T3[], array4: readonly T4[], array5: readonly T5[]): [T1, T2, T3, T4, T5][];
declare function zip<T1, T2, T3, T4>(array1: readonly T1[], array2: readonly T2[], array3: readonly T3[], array4: readonly T4[]): [T1, T2, T3, T4][];
declare function zip<T1, T2, T3>(array1: readonly T1[], array2: readonly T2[], array3: readonly T3[]): [T1, T2, T3][];
declare function zip<T1, T2>(array1: readonly T1[], array2: readonly T2[]): [T1, T2][];
/**
* Creates an object mapping the specified keys to their corresponding
* values.
*
* @see https://radashi.js.org/reference/array/zipToObject
* @example
* ```ts
* zipToObject(['a', 'b'], [1, 2])
* // { a: 1, b: 2 }
*
* zipToObject(['a', 'b'], (k, i) => k + i)
* // { a: 'a0', b: 'b1' }
*
* zipToObject(['a', 'b'], 1)
* // { a: 1, b: 1 }
* ```
* @version 12.1.0
*/
declare function zipToObject<K extends string | number | symbol, V>(keys: readonly K[], values: V | ((key: K, idx: number) => V) | readonly V[]): Record<K, V>;
interface AggregateError extends Error {
errors: any[];
}
interface AggregateErrorConstructor {
new (errors: Iterable<any>, message?: string): AggregateError;
(errors: Iterable<any>, message?: string): AggregateError;
readonly prototype: AggregateError;
}
/**
* The `AggregateError` object represents an error when several errors
* need to be wrapped in a single error.
*
* As this error type is relatively new, it's not available in every
* environment supported by Radashi (last checked on July 20, 2024).
* When it's not globally defined, Radashi provides a polyfill.
*
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AggregateError
* @version 12.2.0
*/
declare const AggregateErrorOrPolyfill: AggregateErrorConstructor;
/**
* Wait for all promises to resolve. Errors from rejected promises are
* collected into an `AggregateError`.
*
* @see https://radashi.js.org/reference/async/all
* @example
* ```ts
* const [user] = await all([
* api.users.create(...),
* s3.buckets.create(...),
* slack.customerSuccessChannel.sendMessage(...)
* ])
* ```
* @version 12.1.0
*/
declare function all<T extends readonly [unknown, ...unknown[]]>(input: T): Promise<{
-readonly [I in keyof T]: Awaited<T[I]>;
}>;
declare function all<T extends readonly unknown[]>(input: T): Promise<{
-readonly [I in keyof T]: Awaited<T[I]>;
}>;
/**
* Check each property in the given object for a promise value. Wait
* for all promises to resolve. Errors from rejected promises are
* collected into an `AggregateError`.
*
* The returned promise will resolve with an object whose keys are
* identical to the keys of the input object. The values are the
* resolved values of the promises.
*
* @see https://radashi.js.org/reference/async/all
* @example
* ```ts
* const { user } = await all({
* user: api.users.create(...),
* bucket: s3.buckets.create(...),
* message: slack.customerSuccessChannel.sendMessage(...)
* })
* ```
*/
declare function all<T extends Record<string, unknown>>(input: T): Promise<{
-readonly [K in keyof T]: Awaited<T[K]>;
}>;
/**
* Useful when for script like things where cleanup should be done on
* fail or success no matter.
*
* You can call defer many times to register many deferred functions
* that will all be called when the function exits in any state.
*
* @see https://radashi.js.org/reference/async/defer
* @example
* ```ts
* const result = await defer(async (defer) => {
* const fileHandle = await openFile('path/to/file')
* defer(() => fileHandle.close())
*
* // Perform operations on the file
* return processFile(fileHandle)
* })
* ```
* @version 12.1.0
*/
declare function defer<TResponse>(func: (register: (fn: (error?: any) => any, options?: {
rethrow?: boolean;
}) => void) => Promise<TResponse>): Promise<TResponse>;
/**
* A helper to try an async function that returns undefined if it
* fails.
*
* @see https://radashi.js.org/reference/async/guard
* @example
* ```ts
* const result = await guard(fetchUsers)() ?? [];
* ```
* @version 12.1.0
*/
declare function guard<TFunction extends () => any>(func: TFunction, shouldGuard?: (err: any) => boolean): GuardReturnType<TFunction>;
type GuardReturnType<TFunction extends () => any> = TFunction extends () => Promise<infer TResolved> ? Promise<TResolved | undefined> : ReturnType<TFunction> | undefined;
/**
* An async map function. Works like the built-in Array.map function
* but handles an async mapper function.
*
* @see https://radashi.js.org/reference/async/map
* @example
* ```ts
* const urls = ['/data1', '/data2', '/data3']
* const responses = await map(urls, async (url) => {
* const response = await fetch('https://api.example.com' + url)
* return response.json()
* })
* ```
* @version 12.1.0
*/
declare function map<T, K>(array: readonly T[], asyncMapFunc: (item: T, index: number) => PromiseLike<K>): Promise<K[]>;
type AbortSignal$1 = {
readonly aborted: boolean;
readonly reason: any;
addEventListener(type: 'abort', listener: () => void): void;
removeEventListener(type: 'abort', listener: () => void): void;
throwIfAborted(): void;
};
type ParallelOptions = {
/**
* The maximum number of functions to run concurrently. If a
* negative number is passed, only one function will run at a time.
* If a number bigger than the array `length` is passed, the array
* length will be used.
*/
limit: number;
signal?: AbortSignal$1;
};
/**
* Executes many async functions in parallel. Returns the results from
* all functions as an array. After all functions have resolved, if
* any errors were thrown, they are rethrown in an instance of
* AggregateError. The operation can be aborted by passing optional AbortSignal,
* which will throw an Error if aborted.
*
* @see https://radashi.js.org/reference/async/parallel
* @example
* ```ts
* // Process images concurrently, resizing each image to a standard size.
* const abortController = new AbortController();
* const images = await parallel(
* {
* limit: 2,
* signal: abortController.signal,
* },
* imageFiles,
* async file => {
* return await resizeImage(file)
* })
*
* // To abort the operation:
* // abortController.abort()
* ```
* @version 12.1.0
*/
declare function parallel<T, K>(options: ParallelOptions | number, array: readonly T[], func: (item: T) => Promise<K>): Promise<K[]>;
/**
* An async reduce function. Works like the built-in Array.reduce
* function but handles an async reducer function.
*
* @see https://radashi.js.org/reference/async/reduce
* @example
* ```ts
* const result = await reduce([1, 2, 3], async (acc, item, index) => {
* return acc + (await computeOnGPU(item))
* }, 0)
* ```
* @version 12.1.0
*/
declare function reduce<T, K>(array: readonly T[], reducer: (acc: K, item: T, index: number) => Promise<K>, initialValue: K): Promise<K>;
declare function reduce<T, K>(array: readonly T[], reducer: (acc: T | K, item: T, index: number) => Promise<K>): Promise<K>;
type AbortSignal = {
throwIfAborted(): void;
};
type RetryOptions = {
times?: number;
delay?: number | null;
backoff?: (count: number) => number;
signal?: AbortSignal;
};
/**
* Retries the given function the specified number of times.
*
* @see https://radashi.js.org/reference/async/retry
* @example
* ```ts
* const abortController = new AbortController();
* const result = await retry({ times: 3, delay: 1000, signal: abortController.signal }, async () => {
* return await fetch('https://example.com')
* })
* // To abort the operation:
* // abortController.abort()
* ```
* @version 12.1.0
*/
declare function retry<TResponse>(options: RetryOptions, func: (exit: (err: any) => void) => Promise<TResponse>): Promise<TResponse>;
/**
* Create a promise that resolves after a given amount of time.
*
* @see https://radashi.js.org/reference/async/sleep
* @example
* ```ts
* await sleep(1000)
* ```
* @version 12.1.0
*/
declare function sleep(milliseconds: number): Promise<void>;
/**
* The `timeout` function creates a promise that rejects after a
* specified delay, with an optional custom error message or error
* function.
*
* @see https://radashi.js.org/reference/async/timeout
* @example
* ```ts
* // Reject after 1000 milliseconds with default message "timeout"
* await timeout(1000)
*
* // Reject after 1000 milliseconds with a custom message
* await timeout(1000, "Optional message")
*
* // Reject after 1000 milliseconds with a custom error
* await timeout(1000, () => new Error("Custom error"))
*
* // Example usage with Promise.race to set a timeout for an asynchronous task
* await Promise.race([
* someAsyncTask(),
* timeout(1000, "Optional message"),
* ])
* ```
* @version 12.3.0
*/
declare function timeout<TError extends Error>(
/**
* The number of milliseconds to wait before rejecting.
*/
ms: number,
/**
* An error message or a function that returns an error. By default,
* a `TimeoutError` is thrown with the message "Operation timed
* out".
*/
error?: string | (() => TError)): Promise<never>;
declare class TimeoutError extends Error {
name: string;
constructor(message?: string);
}
interface BigInt {
/**
* Returns a string representation of an object.
* @param radix Specifies a radix for converting numeric values to strings.
*/
toString(radix?: number): string;
/** Returns a string representation appropriate to the host environment's current locale. */
toLocaleString(locales?: any, options?: BigIntToLocaleStringOptions): string;
/** Returns the primitive value of the specified object. */
valueOf(): bigint;
readonly [Symbol.toStringTag]: "BigInt";
}
/**
* A typed array of 64-bit signed integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated, an exception is raised.
*/
interface BigInt64Array {
/** The size in bytes of each element in the array. */
readonly BYTES_PER_ELEMENT: number;
/** The ArrayBuffer instance referenced by the array. */
readonly buffer: ArrayBufferLike;
/** The length in bytes of the array. */
readonly byteLength: number;
/** The offset in bytes of the array. */
readonly byteOffset: number;
/**
* Returns the this object after copying a section of the array identified by start and end
* to the same array starting at position target
* @param target If target is negative, it is treated as length+target where length is the
* length of the array.
* @param start If start is negative, it is treated as length+start. If end is negative, it
* is treated as length+end.
* @param end If not specified, length of the this object is used as its default value.
*/
copyWithin(target: number, start: number, end?: number): this;
/** Yields index, value pairs for every entry in the array. */
entries(): IterableIterator<[number, bigint]>;
/**
* Determines whether all the members of an array satisfy the specified test.
* @param predicate A function that accepts up to three arguments. The every method calls
* the predicate function for each element in the array until the predicate returns false,
* or until the end of the array.
* @param thisArg An object to which the this keyword can refer in the predicate function.
* If thisArg is omitted, undefined is used as the this value.
*/
every(predicate: (value: bigint, index: number, array: BigInt64Array) => boolean, thisArg?: any): boolean;
/**
* Changes all array elements from `start` to `end` index to a static `value` and returns the modified array
* @param value value to fill array section with
* @param start index to start filling the array at. If start is negative, it is treated as
* length+start where length is the length of the array.
* @param end index to stop filling the array at. If end is negative, it is treated as
* length+end.
*/
fill(value: bigint, start?: number, end?: number): this;
/**
* Returns the elements of an array that meet the condition specified in a callback function.
* @param predicate A function that accepts up to three arguments. The filter method calls
* the predicate function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the predicate function.
* If thisArg is omitted, undefined is used as the this value.
*/
filter(predicate: (value: bigint, index: number, array: BigInt64Array) => any, thisArg?: any): BigInt64Array;
/**
* Returns the value of the first element in the array where predicate is true, and undefined
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found, find
* immediately returns that element value. Otherwise, find returns undefined.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (value: bigint, index: number, array: BigInt64Array) => boolean, thisArg?: any): bigint | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and -1
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found,
* findIndex immediately returns that element index. Otherwise, findIndex returns -1.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: bigint, index: number, array: BigInt64Array) => boolean, thisArg?: any): number;
/**
* Performs the specified action for each element in an array.
* @param callbackfn A function that accepts up to three arguments. forEach calls the
* callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
forEach(callbackfn: (value: bigint, index: number, array: BigInt64Array) => void, thisArg?: any): void;
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: bigint, fromIndex?: number): boolean;
/**
* Returns the index of the first occurrence of a value in an array.
* @param searchElement The value to locate in the array.
* @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the
* search starts at index 0.
*/
indexOf(searchElement: bigint, fromIndex?: number): number;
/**
* Adds all the elements of an array separated by the specified separator string.
* @param separator A string used to separate one element of an array from the next in the
* resulting String. If omitted, the array elements are separated with a comma.
*/
join(separator?: string): string;
/** Yields each index in the array. */
keys(): IterableIterator<number>;
/**
* Returns the index of the last occurrence of a value in an array.
* @param searchElement The value to locate in the array.
* @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the
* search starts at index 0.
*/
lastIndexOf(searchElement: bigint, fromIndex?: number): number;
/** The length of the array. */
readonly length: number;
/**
* Calls a defined callback function on each element of an array, and returns an array that
* contains the results.
* @param callbackfn A function that accepts up to three arguments. The map method calls the
* callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
map(callbackfn: (value: bigint, index: number, array: BigInt64Array) => bigint, thisArg?: any): BigInt64Array;
/**
* Calls the specified callback function for all the elements in an array. The return value of
* the callback function is the accumulated result, and is provided as an argument in the next
* call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduce method calls the
* callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start
* the accumulation. The first call to the callbackfn function provides this value as an argument
* instead of an array value.
*/
reduce(callbackfn: (previousValue: bigint, currentValue: bigint, currentIndex: number, array: BigInt64Array) => bigint): bigint;
/**
* Calls the specified callback function for all the elements in an array. The return value of
* the callback function is the accumulated result, and is provided as an argument in the next
* call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduce method calls the
* callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start
* the accumulation. The first call to the callbackfn function provides this value as an argument
* instead of an array value.
*/
reduce<U>(callbackfn: (previousValue: U, currentValue: bigint, currentIndex: number, array: BigInt64Array) => U, initialValue: U): U;
/**
* Calls the specified callback function for all the elements in an array, in descending order.
* The return value of the callback function is the accumulated result, and is provided as an
* argument in the next call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduceRight method calls
* the callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start
* the accumulation. The first call to the callbackfn function provides this value as an
* argument instead of an array value.
*/
reduceRight(callbackfn: (previousValue: bigint, currentValue: bigint, currentIndex: number, array: BigInt64Array) => bigint): bigint;
/**
* Calls the specified callback function for all the elements in an array, in descending order.
* The return value of the callback function is the accumulated result, and is provided as an
* argument in the next call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduceRight method calls
* the callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start
* the accumulation. The first call to the callbackfn function provides this value as an argument
* instead of an array value.
*/
reduceRight<U>(callbackfn: (previousValue: U, currentValue: bigint, currentIndex: number, array: BigInt64Array) => U, initialValue: U): U;
/** Reverses the elements in the array. */
reverse(): this;
/**
* Sets a value or an array of values.
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set(array: ArrayLike<bigint>, offset?: number): void;
/**
* Returns a section of an array.
* @param start The beginning of the specified portion of the array.
* @param end The end of the specified portion of the array.
*/
slice(start?: number, end?: number): BigInt64Array;
/**
* Determines whether the specified callback function returns true for any element of an array.
* @param predicate A function that accepts up to three arguments. The some method calls the
* predicate function for each element in the array until the predicate returns true, or until
* the end of the array.
* @param thisArg An object to which the this keyword can refer in the predicate function.
* If thisArg is omitted, undefined is used as the this value.
*/
some(predicate: (value: bigint, index: number, array: BigInt64Array) => boolean, thisArg?: any): boolean;
/**
* Sorts the array.
* @param compareFn The function used to determine the order of the elements. If omitted, the elements are sorted in ascending order.
*/
sort(compareFn?: (a: bigint, b: bigint) => number | bigint): this;
/**
* Gets a new BigInt64Array view of the ArrayBuffer store for this array, referencing the elements
* at begin, inclusive, up to end, exclusive.
* @param begin The index of the beginning of the array.
* @param end The index of the end of the array.
*/
subarray(begin?: number, end?: number): BigInt64Array;
/** Converts the array to a string by using the current locale. */
toLocaleString(locales?: string | string[], options?: Intl.NumberFormatOptions): string;
/** Returns a string representation of the array. */
toString(): string;
/** Returns the primitive value of the specified object. */
valueOf(): BigInt64Array;
/** Yields each value in the array. */
values(): IterableIterator<bigint>;
[Symbol.iterator](): IterableIterator<bigint>;
readonly [Symbol.toStringTag]: "BigInt64Array";
[index: number]: bigint;
}
/**
* A typed array of 64-bit unsigned integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated, an exception is raised.
*/
interface BigUint64Array {
/** The size in bytes of each element in the array. */
readonly BYTES_PER_ELEMENT: number;
/** The ArrayBuffer instance referenced by the array. */
readonly buffer: ArrayBufferLike;
/** The length in bytes of the array. */
readonly byteLength: number;
/** The offset in bytes of the array. */
readonly byteOffset: number;
/**
* Returns the this object after copying a section of the array identified by start and end
* to the same array starting at position target
* @param target If target is negative, it is treated as length+target where length is the
* length of the array.
* @param start If start is negative, it is treated as length+start. If end is negative, it
* is treated as length+end.
* @param end If not specified, length of the this object is used as its default value.
*/
copyWithin(target: number, start: number, end?: number): this;
/** Yields index, value pairs for every entry in the array. */
entries(): IterableIterator<[number, bigint]>;
/**
* Determines whether all the members of an array satisfy the specified test.
* @param predicate A function that accepts up to three arguments. The every method calls
* the predicate function for each element in the array until the predicate returns false,
* or until the end of the array.
* @param thisArg An object to which the this keyword can refer in the predicate function.
* If thisArg is omitted, undefined is used as the this value.
*/
every(predicate: (value: bigint, index: number, array: BigUint64Array) => boolean, thisArg?: any): boolean;
/**
* Changes all array elements from `start` to `end` index to a static `value` and returns the modified array
* @param value value to fill array section with
* @param start index to start filling the array at. If start is negative, it is treated as
* length+start where length is the length of the array.
* @param end index to stop filling the array at. If end is negative, it is treated as
* length+end.
*/
fill(value: bigint, start?: number, end?: number): this;
/**
* Returns the elements of an array that meet the condition specified in a callback function.
* @param predicate A function that accepts up to three arguments. The filter method calls
* the predicate function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the predicate function.
* If thisArg is omitted, undefined is used as the this value.
*/
filter(predicate: (value: bigint, index: number, array: BigUint64Array) => any, thisArg?: any): BigUint64Array;
/**
* Returns the value of the first element in the array where predicate is true, and undefined
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found, find
* immediately returns that element value. Otherwise, find returns undefined.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (value: bigint, index: number, array: BigUint64Array) => boolean, thisArg?: any): bigint | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and -1
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found,
* findIndex immediately returns that element index. Otherwise, findIndex returns -1.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: bigint, index: number, array: BigUint64Array) => boolean, thisArg?: any): number;
/**
* Performs the specified action for each element in an array.
* @param callbackfn A function that accepts up to three arguments. forEach calls the
* callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
forEach(callbackfn: (value: bigint, index: number, array: BigUint64Array) => void, thisArg?: any): void;
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: bigint, fromIndex?: number): boolean;
/**
* Returns the index of the first occurrence of a value in an array.
* @param searchElement The value to locate in the array.
* @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the
* search starts at index 0.
*/
indexOf(searchElement: bigint, fromIndex?: number): number;
/**
* Adds all the elements of an array separated by the specified separator string.
* @param separator A string used to separate one element of an array from the next in the
* resulting String. If omitted, the array elements are separated with a comma.
*/
join(separator?: string): string;
/** Yields each index in the array. */
keys(): IterableIterator<number>;
/**
* Returns the index of the last occurrence of a value in an array.
* @param searchElement The value to locate in the array.
* @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the
* search starts at index 0.
*/
lastIndexOf(searchElement: bigint, fromIndex?: number): number;
/** The length of the array. */
readonly length: number;
/**
* Calls a defined callback function on each element of an array, and returns an array that
* contains the results.
* @param callbackfn A function that accepts up to three arguments. The map method calls the
* callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
map(callbackfn: (value: bigint, index: number, array: BigUint64Array) => bigint, thisArg?: any): BigUint64Array;
/**
* Calls the specified callback function for all the elements in an array. The return value of
* the callback function is the accumulated result, and is provided as an argument in the next
* call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduce method calls the
* callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start
* the accumulation. The first call to the callbackfn function provides this value as an argument
* instead of an array value.
*/
reduce(callbackfn: (previousValue: bigint, currentValue: bigint, currentIndex: number, array: BigUint64Array) => bigint): bigint;
/**
* Calls the specified callback function for all the elements in an array. The return value of
* the callback function is the accumulated result, and is provided as an argument in the next
* call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduce method calls the
* callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start
* the accumulation. The first call to the callbackfn function pro