/** * 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(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(array: readonly T[], compareFunc: (a: T, b: T) => T): T | null; type ReadonlyArray2D = 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>(...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(value: T): CastArray; /** * The return type of the {@link castArray} function. * * @see https://radashi.js.org/reference/array/castArray */ type CastArray = [T] extends [never] ? never[] : [unknown] extends [T] ? unknown[] : (T extends any ? T extends readonly (infer U)[] ? U[] : never : never) | (Exclude extends never ? never : Exclude[]); /** * 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(value: T): CastArrayIfExists; /** * The return type of the {@link castArrayIfExists} function. * * @see https://radashi.js.org/reference/array/castArrayIfExists */ type CastArrayIfExists = [T] extends [never] ? never[] : [unknown] extends [T] ? unknown[] | null | undefined : (T extends any ? T extends readonly (infer U)[] ? U[] : never : never) | (Exclude extends never ? never : Exclude[]) | Extract; /** * 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(array: readonly T[], size: Size): Cluster[]; type Cluster = 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[number] extends infer TElement ? (TElement extends readonly (infer TNestedElement)[] ? Exclude : Exclude)[] : 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(...values: T): Concat; /** * Counts the occurrences of each unique value returned by the * `identity` function when applied to each item in the array. * * If no occurrences are found, the key will not be present in the * returned object. * * @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(array: readonly T[], identity: (item: T) => TId): Partial>; /** * 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(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(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(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(array: readonly T[], condition: (item: T) => boolean): [T[], T[]]; /** * Categorizes elements from an `array` into distinct groups. The * function returns an object where each key is a category identifier * determined by the `getGroupId` function, and each value is an array * containing all elements that belong to that category. * * @see https://radashi.js.org/reference/array/group * @example * ```ts * group([1, 2, 3, 4], (n) => n % 2 === 0 ? 'even' : 'odd') * // { even: [2, 4], odd: [1, 3] } * ``` * @version 12.1.0 */ declare function group(array: readonly T[], getGroupId: (item: T, index: number) => 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(listA: readonly T[], listB: readonly T[], identity?: (t: T) => K): boolean; /** * Checks if two arrays are equal in length and content using * `Object.is` comparison. * * @see https://radashi.js.org/reference/array/isArrayEqual * @example * ```ts * _.isArrayEqual([1, 2, 3], [1, 2, 3]) // => true * _.isArrayEqual([1, 2, 3], [1, 2, 4]) // => false * _.isArrayEqual([1, 2], [1, 2, 3]) // => false * _.isArrayEqual([], []) // => true * _.isArrayEqual([NaN], [NaN]) // => true (Object.is handles NaN) * _.isArrayEqual([0], [-0]) // => false (Object.is handles +0 and -0) * ``` * @version 12.7.0 */ declare function isArrayEqual(array1: T[], array2: T[]): 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(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(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. * For nonempty ranges, zero and negative steps throw a RangeError. * * @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(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(array: readonly T[], getKey: (item: T, index: number) => Key, getValue?: (item: T, index: number) => Value): Map; /** * 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(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(array: readonly T[], getKey: (item: T, index: number) => Key, getValue?: (item: T, index: number) => Value): Partial>; /** * 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>(array: readonly T[], mappings: readonly TMapping[]): MappedOutput[]; declare function pluck(array: readonly T[], mappings?: readonly Mapping[]): 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(array: readonly T[], predicate: (value: T) => boolean): T[]; type Defined$1 = T & ({} | null); /** * 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(array: readonly T[], newItem: U, match: (item: T, idx: number) => boolean): (T | Defined$1)[]; type Defined = T & ({} | null); /** * 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(array: readonly T[], newItem: U, match: (a: T, idx: number) => boolean): (T | Defined)[]; /** * 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(array: readonly T[], mapper: (item: T, index: number) => U, condition: ((item: T, index: number) => boolean) | null | undefined): U[]; declare function select(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(array: readonly T[], mapper: (item: T, index: number) => U, condition: (item: T, index: number) => boolean): U | undefined; declare function selectFirst(array: readonly T[], mapper: (item: T, index: number) => U | null | undefined): 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(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(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, "desc") // => [Marlin, Trout, Bass] * ``` * @version 12.1.0 */ declare function sort(array: T, getter?: (item: T[number]) => number, direction?: 'asc' | 'desc'): SortArray; /** * The return type of the `sort` function. Tuple types are preserved. */ type SortArray = T extends readonly [] ? [] : T extends readonly [any, ...infer TRest] ? [T[number], ...SortArrayRest] : T[number][]; type SortArrayRest = T extends readonly [ any, ...infer TRest ] ? [TElement, ...SortArrayRest] : T extends readonly [] ? [] : TElement[]; /** * 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(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(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(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(array1: readonly T1[], array2: readonly T2[], array3: readonly T3[], array4: readonly T4[], array5: readonly T5[]): [T1, T2, T3, T4, T5][]; declare function zip(array1: readonly T1[], array2: readonly T2[], array3: readonly T3[], array4: readonly T4[]): [T1, T2, T3, T4][]; declare function zip(array1: readonly T1[], array2: readonly T2[], array3: readonly T3[]): [T1, T2, T3][]; declare function zip(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(keys: readonly K[], values: V | ((key: K, idx: number) => V) | readonly V[]): Record; /** * 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(input: T): Promise<{ -readonly [I in keyof T]: Awaited; }>; declare function all(input: T): Promise<{ -readonly [I in keyof T]: Awaited; }>; /** * 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>(input: T): Promise<{ -readonly [K in keyof T]: Awaited; }>; /** * 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(func: (register: (fn: (error?: any) => any, options?: { rethrow?: boolean; }) => void) => Promise): Promise; /** * 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 any>(func: TFunction, shouldGuard?: (err: any) => boolean): GuardReturnType; type GuardReturnType any> = TFunction extends () => Promise ? Promise : ReturnType | 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(array: readonly T[], asyncMapFunc: (item: T, index: number) => PromiseLike): Promise; type AbortSignal$2 = { 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$2; }; /** * 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(options: ParallelOptions | number, array: readonly T[], func: (item: T) => Promise): Promise; /** * Queues async function calls by key to ensure sequential execution per key. * Calls with the same key are executed sequentially, while calls with different * keys can run in parallel. * * @see https://radashi.js.org/reference/async/queueByKey * @example * ```ts * const updateUser = async (userId: string, data: object) => { * // API call that should not overlap for the same user * return fetch(`/api/users/${userId}`, { method: 'POST', body: JSON.stringify(data) }) * } * * const queuedUpdate = queueByKey(updateUser, (userId) => userId) * * // These will run sequentially for user123 * queuedUpdate('user123', { name: 'Alice' }) * queuedUpdate('user123', { age: 30 }) * * // This runs in parallel with user123's queue * queuedUpdate('user456', { name: 'Bob' }) * ``` * @version 12.6.0 */ declare function queueByKey(asyncFn: (...args: TArgs) => TResult | PromiseLike, keyFn: (...args: TArgs) => string | number): (...args: TArgs) => Promise; /** * 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(array: readonly T[], reducer: (acc: K, item: T, index: number) => Promise, initialValue: K): Promise; declare function reduce(array: readonly T[], reducer: (acc: T | K, item: T, index: number) => Promise): Promise; type AbortSignal$1 = { throwIfAborted(): void; }; type RetryOptions = { times?: number; delay?: number | null; backoff?: (count: number) => number; signal?: AbortSignal$1; }; /** * 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(options: RetryOptions, func: (exit: (err: any) => void) => Promise): Promise; /** * 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; /** * 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( /** * 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; 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; /** * 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(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(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, 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; [Symbol.iterator](): IterableIterator; 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; /** * 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 provides this value as an argument * instead of an array value. */ reduce(callbackfn: (previousValue: U, currentValue: bigint, currentIndex: number, array: BigUint64Array) => 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: BigUint64Array) => 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(callbackfn: (previousValue: U, currentValue: bigint, currentIndex: number, array: BigUint64Array) => 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, 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): BigUint64Array; /** * 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: BigUint64Array) => 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 BigUint64Array 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): BigUint64Array; /** 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(): BigUint64Array; /** Yields each value in the array. */ values(): IterableIterator; [Symbol.iterator](): IterableIterator; readonly [Symbol.toStringTag]: "BigUint64Array"; [index: number]: bigint; } interface BigIntToLocaleStringOptions { /** * The locale matching algorithm to use.The default is "best fit". For information about this option, see the {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_negotiation Intl page}. */ localeMatcher?: string; /** * The formatting style to use , the default is "decimal". */ style?: string; numberingSystem?: string; /** * The unit to use in unit formatting, Possible values are core unit identifiers, defined in UTS #35, Part 2, Section 6. A subset of units from the full list was selected for use in ECMAScript. Pairs of simple units can be concatenated with "-per-" to make a compound unit. There is no default value; if the style is "unit", the unit property must be provided. */ unit?: string; /** * The unit formatting style to use in unit formatting, the defaults is "short". */ unitDisplay?: string; /** * The currency to use in currency formatting. Possible values are the ISO 4217 currency codes, such as "USD" for the US dollar, "EUR" for the euro, or "CNY" for the Chinese RMB — see the Current currency & funds code list. There is no default value; if the style is "currency", the currency property must be provided. It is only used when [[Style]] has the value "currency". */ currency?: string; /** * How to display the currency in currency formatting. It is only used when [[Style]] has the value "currency". The default is "symbol". * * "symbol" to use a localized currency symbol such as €, * * "code" to use the ISO currency code, * * "name" to use a localized currency name such as "dollar" */ currencyDisplay?: string; /** * Whether to use grouping separators, such as thousands separators or thousand/lakh/crore separators. The default is true. */ useGrouping?: boolean; /** * The minimum number of integer digits to use. Possible values are from 1 to 21; the default is 1. */ minimumIntegerDigits?: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21; /** * The minimum number of fraction digits to use. Possible values are from 0 to 20; the default for plain number and percent formatting is 0; the default for currency formatting is the number of minor unit digits provided by the {@link http://www.currency-iso.org/en/home/tables/table-a1.html ISO 4217 currency codes list} (2 if the list doesn't provide that information). */ minimumFractionDigits?: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20; /** * The maximum number of fraction digits to use. Possible values are from 0 to 20; the default for plain number formatting is the larger of minimumFractionDigits and 3; the default for currency formatting is the larger of minimumFractionDigits and the number of minor unit digits provided by the {@link http://www.currency-iso.org/en/home/tables/table-a1.html ISO 4217 currency codes list} (2 if the list doesn't provide that information); the default for percent formatting is the larger of minimumFractionDigits and 0. */ maximumFractionDigits?: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20; /** * The minimum number of significant digits to use. Possible values are from 1 to 21; the default is 1. */ minimumSignificantDigits?: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21; /** * The maximum number of significant digits to use. Possible values are from 1 to 21; the default is 21. */ maximumSignificantDigits?: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21; /** * The formatting that should be displayed for the number, the defaults is "standard" * * "standard" plain number formatting * * "scientific" return the order-of-magnitude for formatted number. * * "engineering" return the exponent of ten when divisible by three * * "compact" string representing exponent, defaults is using the "short" form */ notation?: string; /** * used only when notation is "compact" */ compactDisplay?: string; } type Awaitable = T | PromiseLike; /** * Represents values that are considered "falsy" in JavaScript. These * values cause the condition in an `if` statement or ternary * expression to be false, leading to the execution of the `else` * branch. */ type Falsy = null | undefined | false | '' | 0 | 0n; /** * The `Any` class does not exist at runtime. It's used in type * definitions to detect an `any` type. * * ```ts * type IsAny = [T] extends [Any] ? 'is any' : 'is not any' * ``` */ declare class Any { private any; } /** * Represents a class constructor. */ type Class = new (...args: TArgs) => TReturn; /** * Extracts `T` if `T` is not `any`, otherwise `never`. * * ```ts * type A = ExtractNotAny * // ^? never * type B = ExtractNotAny * // ^? string * ``` */ type ExtractNotAny = Extract<[T] extends [Any] ? never : T, U>; type SwitchAny = [T] extends [Any] ? U : T; type SwitchNever = [T] extends [never] ? U : T; /** * Extract types in `T` that are assignable to `U`. Coerce `any` and * `never` types to unknown. */ type StrictExtract = SwitchNever, U>, unknown>; /** * Resolve a type union of property name literals within type `T` * whose property values are assignable to type `TConstraint`. If `T` * is a primitive, it's first transformed into its boxed equivalent * (e.g. `string` becomes `String`, `number` becomes `Number`, and so * on). * * Use case: “I want to know which properties of `T` are compatible * with `TConstraint`.” */ type CompatibleProperty = [T] extends [Any] ? keyof any : T extends null | undefined ? never : (T extends object ? T : BoxedPrimitive) extends infer TObject ? { [P in keyof TObject]: TObject[P] extends TConstraint ? P : never; }[keyof TObject] : never; /** * A value that can be reliably compared with JavaScript comparison * operators (e.g. `>`, `>=`, etc). */ type Comparable = number | string | bigint | { valueOf: () => number | string | bigint; } | { [Symbol.toPrimitive](hint: 'number'): number; } | { [Symbol.toPrimitive](hint: 'string'): string; }; /** * Extract a string union of property names from type `T` whose value * can be compared with `>`, `>=`, etc. */ type ComparableProperty = CompatibleProperty; /** * A comparator function. It can be passed to the `sort` method of * arrays to sort the elements. * * Return a negative number to sort the “left” value before the “right” * value, a positive number to sort the “right” value before the “left” * value, and 0 to keep the order of the values. */ type Comparator = (left: T, right: T) => number; /** Convert a union to an intersection */ type Intersect = (U extends any ? (k: U) => void : never) extends (k: infer I) => void ? I : never; /** * Useful to flatten the type output to improve type hints shown in * editors. And also to transform an interface into a type to aide * with assignability. * * @see https://github.com/microsoft/TypeScript/issues/15300 */ type Simplify = {} & { [P in keyof T]: T[P]; }; /** * A result tuple where the error is `undefined`. * * @example * ```ts * type GoodResult = Ok * // ^? [undefined, string] * ``` */ type Ok = [err: undefined, result: TResult]; /** * A result tuple where an error is included. * * Note that `TError` is non-nullable, which means that * `Err` and `Err` are not valid. * * @example * ```ts * type BadResult = Err * // ^? [Error, undefined] * * type BadResult2 = Err * // ^? [TypeError | MyCoolCustomError, undefined] * ``` */ type Err = [err: TError, result: undefined]; /** * A result tuple. * * First index is the error, second index is the result. * * @example * ```ts * type MyResult = Result * // ^? Ok | Err * * type MyResult2 = Result * // ^? Ok | Err * ``` */ type Result = Ok | Err; /** * A promise that resolves to a result tuple. * * @example * ```ts * type MyResult = ResultPromise * // ^? Promise | Err> * * type MyResult2 = ResultPromise * // ^? Promise | Err> * ``` */ type ResultPromise = Promise<[ TError ] extends [never] ? Ok : [TResult] extends [never] ? Err : Result>; /** * Get all properties **not using** the `?:` type operator. */ type RequiredKeys = T extends any ? keyof T extends infer K ? K extends keyof T ? Omit extends T ? never : K : never : never : never; /** * Get all properties using the `?:` type operator. */ type OptionalKeys = T extends any ? keyof T extends infer K ? K extends keyof T ? Omit extends T ? K : never : never : never : never; /** * Resolves to `true` if `Left` and `Right` are exactly the same type. * * Otherwise false. */ type IsExactType = [Left] extends [Any] ? [Right] extends [Any] ? true : false : (() => U extends Left ? 1 : 0) extends () => U extends Right ? 1 : 0 ? true : false; type Primitive = number | string | boolean | symbol | bigint | null | undefined | void; /** * Coerce a primitive type to its boxed equivalent. * * @example * ```ts * type A = BoxedPrimitive * // ^? String * type B = BoxedPrimitive * // ^? Number * ``` */ type BoxedPrimitive = T extends string ? String : T extends number ? Number : T extends boolean ? Boolean : T extends bigint ? BigInt : T extends symbol ? Symbol : never; type TypedArray = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array | BigInt64Array | BigUint64Array | DataView | ArrayBuffer | SharedArrayBuffer; /** * Add your own classes to this registry by extending its interface * with what's called “declaration merging” in TypeScript. * * All property types in this registry type may be treated specially * by any of Radashi's complex types. For example, `assign` will avoid * merging with types in this registry. */ interface CustomClassRegistry { } /** * This type represents any custom class that was "registered" through * the `CustomClassRegistry` type. */ type CustomClass = CustomClassRegistry[keyof CustomClassRegistry]; /** * These types are implemented natively. * * Note that boxed primitives like `Boolean` (different from * `boolean`) are not included, because `boolean extends Boolean ? 1 : * 0` resolves to 1. */ type BuiltInType = ES2021.BuiltInType | WebAPI.BuiltInType | NodeJS.BuiltInType; declare namespace ES2020 { type BuiltInType = Primitive | Promise | Date | RegExp | Error | readonly any[] | ReadonlyMap | ReadonlySet | WeakMap | WeakSet | TypedArray | Function; } declare namespace ES2021 { type BuiltInType = ES2020.BuiltInType | GlobalObjectType<'FinalizationRegistry'> | GlobalObjectType<'WeakRef'>; } declare namespace NodeJS { type BuiltInType = GlobalObjectType<'Buffer'>; } declare namespace WebAPI { type BuiltInType = GlobalObjectType<'AbortController'> | GlobalObjectType<'AbortSignal'> | GlobalObjectType<'Blob'> | GlobalObjectType<'Body'> | GlobalObjectType<'CompressionStream'> | GlobalObjectType<'Crypto'> | GlobalObjectType<'CustomEvent'> | GlobalObjectType<'DecompressionStream'> | GlobalObjectType<'Event'> | GlobalObjectType<'EventTarget'> | GlobalObjectType<'FormData'> | GlobalObjectType<'Headers'> | GlobalObjectType<'MessageChannel'> | GlobalObjectType<'Navigator'> | GlobalObjectType<'ReadableStream'> | GlobalObjectType<'ReadableStreamBYOBReader'> | GlobalObjectType<'ReadableStreamDefaultController'> | GlobalObjectType<'ReadableStreamDefaultReader'> | GlobalObjectType<'SubtleCrypto'> | GlobalObjectType<'TextDecoder'> | GlobalObjectType<'TextDecoderStream'> | GlobalObjectType<'TextEncoder'> | GlobalObjectType<'TextEncoderStream'> | GlobalObjectType<'TransformStream'> | GlobalObjectType<'TransformStreamDefaultController'> | GlobalObjectType<'URL'> | GlobalObjectType<'URLSearchParams'> | GlobalObjectType<'WebSocket'> | GlobalObjectType<'WritableStream'> | GlobalObjectType<'WritableStreamDefaultController'> | GlobalObjectType<'WritableStreamDefaultWriter'> | WebDocumentAPI.BuiltInType; } declare namespace WebDocumentAPI { type BuiltInType = GlobalObjectType<'Node'> | GlobalObjectType<'NodeList'> | GlobalObjectType<'NodeIterator'> | GlobalObjectType<'HTMLCollection'> | GlobalObjectType<'CSSStyleDeclaration'> | GlobalObjectType<'DOMStringList'> | GlobalObjectType<'DOMTokenList'>; } type GlobalObjectType = [Identifier] extends [Any] ? never : keyof Identifier extends never ? never : typeof globalThis extends { [P in Identifier]: any; } ? InstanceType<(typeof globalThis)[Identifier]> : never; /** * Converts a `PromiseLike` to a `Promise`. * * Note: If the given promise throws a non-Error value, it will be * rethrown. * * @see https://radashi.js.org/reference/async/toResult * @example * ```ts * import { toResult, Result } from 'radashi' * * const good = async (): Promise => 1 * const bad = async (): Promise => { throw new Error('bad') } * * const goodResult = await toResult(good()) * // => [undefined, 1] * * const badResult = await toResult(bad()) * // => [Error('bad'), undefined] * ``` * @version 12.4.0 */ declare function toResult(promise: PromiseLike): Promise>; /** * The result of a `tryit` function. * * If the function returns a promise, the result is a promise that * resolves to an error-first callback-_like_ array response as * `[Error, result]`. * * If the function returns a non-promise, the result is an error-first * callback-_like_ array response as `[Error, result]`. * * @see https://radashi.js.org/reference/async/tryit * @example * ```ts * const [err, result] = await tryit(async () => { * return await fetch('https://example.com') * }) * ``` * @version 12.1.0 */ type TryitResult = TReturn extends PromiseLike ? ResultPromise : Result; /** * A helper to try an async function without forking the control flow. * Returns an error-first callback-_like_ array response as `[Error, * result]` */ declare function tryit(func: (...args: TArgs) => TReturn): (...args: TArgs) => TryitResult; interface PromiseWithResolvers { promise: Promise; resolve: (value: T | PromiseLike) => void; reject: (reason?: any) => void; } /** * Creates a new promise and returns the resolve and reject functions along with the promise itself. * * The ponyfill for https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/withResolvers * * @see https://radashi.js.org/reference/async/withResolvers * @example * ```ts * const {resolve, reject, promise} = withResolvers() * * resolve(42) * ``` * @version 12.2.0 */ declare function withResolvers(): PromiseWithResolvers; /** * Creates a memoized function for async operations. This function caches results * to avoid redundant executions of expensive async operations. The source function * only runs when no cached result exists for the given arguments. When a TTL * (time-to-live in milliseconds) is specified, cached results will expire after * the designated time period, triggering a fresh execution on subsequent calls. * * @see https://radashi.js.org/reference/async/promiseMemo * @example * ```ts * const calls: number[] = [] * const fetchUser = promiseMemo( * async (id: number) => { * calls.push(id) * * // Simuate network delay * await new Promise(resolve => setTimeout(resolve, 100)) * * return { * id, * name: `User-${id}`, * } * }, * { ttl: 5000 }, * ) * * // First call * await fetchUser(1) // { id: 1, name: 'User 1' } * * // Doesn't trigger API call, returns cached result * await fetchUser(1) // { id: 1, name: 'User 1' } * * // calls array * console.log(calls) // [1] * ``` * @version 13.0.0 */ declare function promiseMemo Promise>(func: TFunc, options?: MemoOptions): Memoized; /** * Make an object callable. Given an object and a function the * returned object will be a function with all the objects properties. * * @see https://radashi.js.org/reference/curry/callable * @example * ```ts * const car = callable({ * wheels: 2 * }, self => () => { * return 'driving' * }) * * car.wheels // => 2 * car() // => 'driving' * ``` * @version 12.1.0 */ declare function callable, TFunc extends (...args: any) => any>(obj: TObj, fn: (self: TObj) => TFunc): TObj & TFunc; /** * Create a function that chains multiple functions together. The * functions are called in order. Each function takes the result of * the previous function as its first argument. * * @see https://radashi.js.org/reference/curry/chain * @example * ```ts * const myChainedFunc = chain( * (x) => x + 5, * (x) => x * 2, * ) * * myChainedFunc(0) * // => 10 * ``` * @version 12.1.0 */ declare function chain(f1: (...arg: T1) => T2, f2: (arg: T2) => T3): (...arg: T1) => T3; declare function chain(f1: (...arg: T1) => T2, f2: (arg: T2) => T3, f3: (arg: T3) => T4): (...arg: T1) => T4; declare function chain(f1: (...arg: T1) => T2, f2: (arg: T2) => T3, f3: (arg: T3) => T4, f4: (arg: T4) => T5): (...arg: T1) => T5; declare function chain(f1: (...arg: T1) => T2, f2: (arg: T2) => T3, f3: (arg: T3) => T4, f4: (arg: T4) => T5, f5: (arg: T5) => T6): (...arg: T1) => T6; declare function chain(f1: (...arg: T1) => T2, f2: (arg: T2) => T3, f3: (arg: T3) => T4, f4: (arg: T4) => T5, f5: (arg: T5) => T6, f6: (arg: T6) => T7): (...arg: T1) => T7; declare function chain(f1: (...arg: T1) => T2, f2: (arg: T2) => T3, f3: (arg: T3) => T4, f4: (arg: T4) => T5, f5: (arg: T5) => T6, f6: (arg: T6) => T7, f7: (arg: T7) => T8): (...arg: T1) => T8; declare function chain(f1: (...arg: T1) => T2, f2: (arg: T2) => T3, f3: (arg: T3) => T4, f4: (arg: T4) => T5, f5: (arg: T5) => T6, f6: (arg: T6) => T7, f7: (arg: T7) => T8, f8: (arg: T8) => T9): (...arg: T1) => T9; declare function chain(f1: (...arg: T1) => T2, f2: (arg: T2) => T3, f3: (arg: T3) => T4, f4: (arg: T4) => T5, f5: (arg: T5) => T6, f6: (arg: T6) => T7, f7: (arg: T7) => T8, f8: (arg: T8) => T9, f9: (arg: T9) => T10): (...arg: T1) => T10; declare function chain(f1: (...arg: T1) => T2, f2: (arg: T2) => T3, f3: (arg: T3) => T4, f4: (arg: T4) => T5, f5: (arg: T5) => T6, f6: (arg: T6) => T7, f7: (arg: T7) => T8, f8: (arg: T8) => T9, f9: (arg: T9) => T10, f10: (arg: T10) => T11): (...arg: T1) => T11; /** * Create a function that composes multiple functions together. In a * composition of functions, each function is given the next function * as an argument and must call it to continue executing. * * @see https://radashi.js.org/reference/curry/compose * @example * ```ts * const myComposedFunc = compose( * (x) => x + 5, * (x) => x * 2, * ) * * myComposedFunc(0) * // => 5 * ``` * @version 12.1.0 */ declare function compose(f1: (next: (...args: F1NextArgs) => LastResult) => (...args: F1Args) => F1Result, last: (...args: F1NextArgs) => LastResult): (...args: F1Args) => F1Result; declare function compose(f1: (next: (...args: F1NextArgs) => F2Result) => (...args: F1Args) => F1Result, f2: (next: (...args: F2NextArgs) => LastResult) => (...args: F1NextArgs) => F2Result, last: (...args: F2NextArgs) => LastResult): (...args: F1Args) => F1Result; declare function compose(f1: (next: (...args: F1NextArgs) => F2Result) => (...args: F1Args) => F1Result, f2: (next: (...args: F2NextArgs) => F3Result) => (...args: F1NextArgs) => F2Result, f3: (next: (...args: F3NextArgs) => LastResult) => (...args: F2NextArgs) => F3Result, last: (...args: F3NextArgs) => LastResult): (...args: F1Args) => F1Result; declare function compose(f1: (next: (...args: F1NextArgs) => F2Result) => (...args: F1Args) => F1Result, f2: (next: (...args: F2NextArgs) => F3Result) => (...args: F1NextArgs) => F2Result, f3: (next: (...args: F3NextArgs) => F4Result) => (...args: F2NextArgs) => F3Result, f4: (next: (...args: F4NextArgs) => LastResult) => (...args: F3NextArgs) => F4Result, last: (...args: F4NextArgs) => LastResult): (...args: F1Args) => F1Result; declare function compose(f1: (next: (...args: F1NextArgs) => F2Result) => (...args: F1Args) => F1Result, f2: (next: (...args: F2NextArgs) => F3Result) => (...args: F1NextArgs) => F2Result, f3: (next: (...args: F3NextArgs) => F4Result) => (...args: F2NextArgs) => F3Result, f4: (next: (...args: F4NextArgs) => F5Result) => (...args: F3NextArgs) => F4Result, f5: (next: (...args: F5NextArgs) => LastResult) => (...args: F4NextArgs) => F5Result, last: (...args: F5NextArgs) => LastResult): (...args: F1Args) => F1Result; declare function compose(f1: (next: (...args: F1NextArgs) => F2Result) => (...args: F1Args) => F1Result, f2: (next: (...args: F2NextArgs) => F3Result) => (...args: F1NextArgs) => F2Result, f3: (next: (...args: F3NextArgs) => F4Result) => (...args: F2NextArgs) => F3Result, f4: (next: (...args: F4NextArgs) => F5Result) => (...args: F3NextArgs) => F4Result, f5: (next: (...args: F5NextArgs) => F6Result) => (...args: F4NextArgs) => F5Result, f6: (next: (...args: F6NextArgs) => LastResult) => (...args: F5NextArgs) => F6Result, last: (...args: F6NextArgs) => LastResult): (...args: F1Args) => F1Result; declare function compose(f1: (next: (...args: F1NextArgs) => F2Result) => (...args: F1Args) => F1Result, f2: (next: (...args: F2NextArgs) => F3Result) => (...args: F1NextArgs) => F2Result, f3: (next: (...args: F3NextArgs) => F4Result) => (...args: F2NextArgs) => F3Result, f4: (next: (...args: F4NextArgs) => F5Result) => (...args: F3NextArgs) => F4Result, f5: (next: (...args: F5NextArgs) => F6Result) => (...args: F4NextArgs) => F5Result, f6: (next: (...args: F6NextArgs) => F7Result) => (...args: F5NextArgs) => F6Result, f7: (next: (...args: F7NextArgs) => LastResult) => (...args: F6NextArgs) => F7Result, last: (...args: F7NextArgs) => LastResult): (...args: F1Args) => F1Result; declare function compose(f1: (next: (...args: F1NextArgs) => F2Result) => (...args: F1Args) => F1Result, f2: (next: (...args: F2NextArgs) => F3Result) => (...args: F1NextArgs) => F2Result, f3: (next: (...args: F3NextArgs) => F4Result) => (...args: F2NextArgs) => F3Result, f4: (next: (...args: F4NextArgs) => F5Result) => (...args: F3NextArgs) => F4Result, f5: (next: (...args: F5NextArgs) => F6Result) => (...args: F4NextArgs) => F5Result, f6: (next: (...args: F6NextArgs) => F7Result) => (...args: F5NextArgs) => F6Result, f7: (next: (...args: F7NextArgs) => LastResult) => (...args: F6NextArgs) => F7Result, f8: (next: (...args: F8NextArgs) => LastResult) => (...args: F7NextArgs) => F8Result, last: (...args: F8NextArgs) => LastResult): (...args: F1Args) => F1Result; declare function compose(f1: (next: (...args: F1NextArgs) => F2Result) => (...args: F1Args) => F1Result, f2: (next: (...args: F2NextArgs) => F3Result) => (...args: F1NextArgs) => F2Result, f3: (next: (...args: F3NextArgs) => F4Result) => (...args: F2NextArgs) => F3Result, f4: (next: (...args: F4NextArgs) => F5Result) => (...args: F3NextArgs) => F4Result, f5: (next: (...args: F5NextArgs) => F6Result) => (...args: F4NextArgs) => F5Result, f6: (next: (...args: F6NextArgs) => F7Result) => (...args: F5NextArgs) => F6Result, f7: (next: (...args: F7NextArgs) => LastResult) => (...args: F6NextArgs) => F7Result, f8: (next: (...args: F8NextArgs) => LastResult) => (...args: F7NextArgs) => F8Result, f9: (next: (...args: F9NextArgs) => LastResult) => (...args: F8NextArgs) => F9Result, last: (...args: F9NextArgs) => LastResult): (...args: F1Args) => F1Result; interface DebounceFunction { (...args: TArgs): TReturn; /** * Prevent the scheduled call from happening, if any. */ cancel(): void; /** * If a debounced call is scheduled, this invokes it immediately. */ flush(): void; /** * Returns true if a debounced call is scheduled. */ isDebounced(): boolean; /** * The underlying function */ readonly callee: (...args: TArgs) => unknown; } type Debounced any> = DebounceFunction> & { callee: TCallee; }; interface DebounceOptions { delay: number; /** * When true, your callback is invoked immediately the very first * time the debounced function is called. After that, the debounced * function works as if `leading` was `false`. * * @default false */ leading?: boolean; } /** * Returns a new function that will only call the source function * after `delay` milliseconds have passed without any invocations. * * See the documentation (or the `DebounceFunction` type) for details * on the methods and properties available on the returned function. * * @see https://radashi.js.org/reference/curry/debounce * @example * ```ts * const myDebouncedFunc = debounce({ delay: 1000 }, (x) => { * console.log(x) * }) * * myDebouncedFunc(0) // Nothing happens * myDebouncedFunc(1) // Nothing happens * // Logs "1" about 1 second after the last invocation * ``` * @version 12.1.0 */ declare function debounce any>({ delay, leading }: DebounceOptions, callee: TCallee): Debounced; /** * Flip the first two arguments of a function. * * @see https://radashi.js.org/reference/curry/flip * @example * ```ts * const subtract = (x: number, y: number) => x - y * * // Equivalent to “y - x” * const flippedSubtract = flip(subtract) * * flippedSubtract(3, 4) * // => 1 * ``` * @version 12.2.0 */ declare function flip(fn: (...args: Args) => Result): (...args: Flip) => Result; type Flip = T extends [infer A, infer B, ...infer R] ? [B, A, ...R] : never; type MemoCache = Record; type Memoized any> = (...args: Parameters) => ReturnType; interface MemoOptions any> { cache?: MemoCache>; key?: (...args: Parameters) => string; ttl?: number; } /** * Creates a memoized function. The returned function will only * execute the source function when no value has previously been * computed. If a ttl (milliseconds) is given previously computed * values will be checked for expiration before being returned. * * @see https://radashi.js.org/reference/curry/memo * @example * ```ts * const calls: number[] = [] * const fib = memo((x: number) => { * calls.push(x) * return x < 2 ? x : fib(x - 1) + fib(x - 2) * }) * * fib(10) // 55 * fib(10) // 55 * // calls === [10] * * fib(11) // 89 * // calls === [10, 11] * ``` * @version 12.1.0 */ declare function memo any>(func: TFunc, options?: MemoOptions>): Memoized; /** * Creates a memoized version of a function that caches only its most * recent call. * * When the function is called with the same arguments as the previous * call, it returns the cached result instead of recalculating. This * is useful for optimizing expensive calculations when only the * latest result needs to be cached, making it more memory-efficient * than traditional memoization. * * @see https://radashi.js.org/reference/curry/memoLastCall * @example * ```ts * const expensiveCalculation = (x: number, y: number): number => { * console.log('Calculating...'); * return x + y; * }; * * const memoizedCalc = memoLastCall(expensiveCalculation); * * console.log(memoizedCalc(2, 3)); // Outputs: "Calculating..." then 5 * console.log(memoizedCalc(2, 3)); // Outputs: 5 (uses cached result) * console.log(memoizedCalc(3, 4)); // Outputs: "Calculating..." then 7 * console.log(memoizedCalc(2, 3)); // Outputs: "Calculating..." then 5 (previous cache was overwritten) * ``` * @version 12.4.0 */ declare function memoLastCall(fn: (...args: Args) => Result): (...args: Args) => Result; /** * The type of a function wrapped with `once`. * @version 12.2.0 */ type OnceFunction = (this: This, ...args: Args) => Return; /** * Create a function that runs at most once, no matter how many times * it's called. If it was already called before, returns the result * from the first call. This is a lighter version of `memo()`. * * To allow your `once`-wrapped function to be called again, see the * `once.reset` function. * * @see https://radashi.js.org/reference/curry/once * @example * ```ts * const fn = once(() => Math.random()) * fn() // 0.5 * fn() // 0.5 * ``` */ declare const once: Once; type Once = { (fn: (this: This, ...args: Args) => Return): (this: This, ...args: Args) => Return; /** * Reset the result of a function that was created with `once`, * allowing it to be called again. * * ```ts * const fn = once(() => Math.random()) * fn() // 0.5 * fn() // 0.5 * once.reset(fn) * fn() // 0.3 * fn() // 0.3 * ``` */ reset(fn: OnceFunction): void; }; /** * This type produces the type array of `TItems` with all the type items * in `TItemsToRemove` removed from the start of the array type. * * ```ts * type T = RemoveItemsInFront<[number, number], [number]> * // [number] * * type T = RemoveItemsInFront<[File, number, string], [File, number]> * // [string] * ``` * @version 12.1.0 */ type RemoveItemsInFront = TItems extends [...TItemsToRemove, ...infer TRest] ? TRest : TItems; /** * Create a partial function by providing some (or all) of the * arguments the given function needs. * * @see https://radashi.js.org/reference/curry/partial * @example * ```ts * const add = (a: number, b: number) => a + b * * const addFive = partial(add, 5) * * addFive(2) // => 7 * ``` */ declare function partial, R>(fn: (...args: T) => R, ...args: TA): (...rest: RemoveItemsInFront) => R; /** * Like partial but for unary functions that accept a single object * argument * * @see https://radashi.js.org/reference/curry/partob * @example * ```ts * const add = ( * {a = 0, b = 0, c = 0}: { * a?: number, * b?: number, * c?: number * } * ) => a + b + c * * const addPartial = partob(add, { a: 1 }) * addPartial({ b: 2 }) // 3 * addPartial({ b: 1, c: 5 }) // 7 * ``` * @version 12.1.0 */ declare function partob>(fn: (args: T) => K, argObj: PartialArgs): (restObj: Omit) => K; /** * Creates a function that executes multiple functions in the same * order as they are passed in arguments. Each function may be * synchronous or asynchronous. The result of each function is passed * to the next function. The final result is returned as a `Promise`. * * @see https://radashi.js.org/reference/curry/promiseChain * @example * ```ts * const chained = promiseChain( * (x: number, y: number) => x + y * async (n: number) => n * 2 * async (n: number) => `Your Value is ${n}` * ) * * await chained(2, 3) // "Your Value is 10" * ``` * @version 12.6.0 */ declare function promiseChain(f1: (...args: T1) => Awaitable, f2: (arg: T2) => Awaitable): (...arg: T1) => Promise; declare function promiseChain(f1: (...args: T1) => Awaitable, f2: (arg: T2) => Awaitable, f3: (arg: T3) => Awaitable): (...args: T1) => Promise; declare function promiseChain(f1: (...args: T1) => Awaitable, f2: (args: T2) => Awaitable, f3: (args: T3) => Awaitable, f4: (args: T4) => Awaitable): (...args: T1) => Promise; declare function promiseChain(f1: (...args: T1) => Awaitable, f2: (args: T2) => Awaitable, f3: (args: T3) => Awaitable, f4: (args: T4) => Awaitable, f5: (args: T5) => Awaitable): (...args: T1) => Promise; declare function promiseChain(f1: (...args: T1) => Awaitable, f2: (args: T2) => Awaitable, f3: (args: T3) => Awaitable, f4: (args: T4) => Awaitable, f5: (args: T5) => Awaitable, f6: (args: T6) => Awaitable): (...args: T1) => Promise; declare function promiseChain(f1: (...args: T1) => Awaitable, f2: (args: T2) => Awaitable, f3: (args: T3) => Awaitable, f4: (args: T4) => Awaitable, f5: (args: T5) => Awaitable, f6: (args: T6) => Awaitable, f7: (args: T7) => Awaitable): (...args: T1) => Promise; declare function promiseChain(f1: (...args: T1) => Awaitable, f2: (args: T2) => Awaitable, f3: (args: T3) => Awaitable, f4: (args: T4) => Awaitable, f5: (args: T5) => Awaitable, f6: (args: T6) => Awaitable, f7: (args: T7) => Awaitable, f8: (args: T8) => Awaitable): (...args: T1) => Promise; declare function promiseChain(f1: (...args: T1) => Awaitable, f2: (args: T2) => Awaitable, f3: (args: T3) => Awaitable, f4: (args: T4) => Awaitable, f5: (args: T5) => Awaitable, f6: (args: T6) => Awaitable, f7: (args: T7) => Awaitable, f8: (args: T8) => Awaitable, f9: (args: T9) => Awaitable): (...args: T1) => Promise; declare function promiseChain(f1: (...args: T1) => Awaitable, f2: (args: T2) => Awaitable, f3: (args: T3) => Awaitable, f4: (args: T4) => Awaitable, f5: (args: T5) => Awaitable, f6: (args: T6) => Awaitable, f7: (args: T7) => Awaitable, f8: (args: T8) => Awaitable, f9: (args: T9) => Awaitable, f10: (args: T10) => Awaitable): (...args: T1) => Promise; interface PromiseDebounceFunction extends DebounceFunction> { /** * If a debounced call is scheduled, this invokes it immediately and * returns its promise. Otherwise, it returns `undefined`. */ flush(): Promise | undefined; } type PromiseDebounced any> = PromiseDebounceFunction, Awaited>> & { callee: TCallee; }; /** * Same as `debounce`, but a promise is returned that resolves with * the result if that call was the last one. * * See the documentation (or the `PromiseDebounceFunction` type) for * details on the methods and properties available on the returned * function. * * @see https://radashi-org.github.io/reference/curry/promiseDebounce * @example * ```ts * const myDebouncedFunc = promiseDebounce({ delay: 1000 }, (x) => x + 1) * * myDebouncedFunc(0).then(x => console.log(x)) * myDebouncedFunc(1).then(x => console.log(x)) * // Logs "2" * ``` */ declare function promiseDebounce any>({ delay, leading }: DebounceOptions, callee: TCallee): PromiseDebounced; /** * Creates a Proxy object that will dynamically call the handler * argument when attributes are accessed. * * @see https://radashi.js.org/reference/curry/proxied * @example * ```ts * const proxy = proxied(propertyName => propertyName.toUpperCase()) * proxy.foo // => "FOO" * ``` * @version 12.1.0 */ declare function proxied(handler: (propertyName: T) => K): Record; type ThrottledFunction = { (...args: TArgs): void; /** * Checks if there is any invocation throttled */ isThrottled(): boolean; /** * Call the throttled function immediately, ignoring any throttling * that may be in effect. After, a new throttled call will be allowed * after the interval has passed. * * @example * ```ts * const logMessage = (message: string) => { * console.log(`Message: ${message}`) * } * const throttledLog = throttle({ interval: 1000 }, logMessage) * * throttledLog('First call') // Logs immediately * throttledLog('Throttled') // Doesn't log (throttled) * * // Force a log, bypassing the throttle * throttledLog.trigger('Forced log') // Logs immediately * * // Check if it's still throttled * throttledLog.isThrottled() // => true * ``` */ trigger(...args: TArgs): void; }; /** * Given an interval and a function returns a new function that will * only call the source function if interval milliseconds have passed * since the last invocation. * * @see https://radashi.js.org/reference/curry/throttle * @example * ```ts * const sup = throttle({ interval: 1000 }, () => { * console.log("sup") * }) * sup() // => logs "sup" * sup() // => no logs * setTimeout(() => sup(), 500) // => no logs * setTimeout(() => sup(), 1000) // => logs "sup" * ``` * @version 12.1.0 */ declare function throttle({ interval, trailing }: { interval: number; trailing?: boolean; }, func: (...args: TArgs) => any): ThrottledFunction; /** * Create a function that always returns the same value. * * @example * ```ts * const alwaysTrue = always(true) * alwaysTrue() // true * alwaysTrue() // true * alwaysTrue() // true * ``` * @version 12.2.0 */ declare function always(value: T): () => T; /** * Cast a value into a comparator function. * * - **Function**: If `mapping` is a function, it maps the input * values to a comparable value. * - **Property Name**: If `mapping` is a property name, it maps the * input values to a property of the input values with a comparable * value. * * Optionally, you can pass a custom `compare` function that receives * the mapped values and returns a number. If not provided, values are * compared with the `<` and `>` built-in operators. A positive number * means the “right value” is greater than the “left value”, a * negative number means the “left value” is greater than the “right * value”, and 0 means both values are equal. * * @see https://radashi.js.org/reference/function/castComparator * @example * ```ts * const compareUserNames = castComparator( * (user) => user.name, * (a, b) => b.localeCompare(a), * ) * * const users = [ * { name: 'John', age: 20 }, * { name: 'Jane', age: 25 }, * { name: 'Doe', age: 22 }, * ] * * users.sort(compareUserNames) * // => [Doe, Jane, John] * ``` * @version 12.2.0 */ declare function castComparator(mapping: TMapping, compare?: null | undefined, reverse?: boolean): Comparator>; declare function castComparator>(mapping: TMapping, compare: Comparator, reverse?: boolean): Comparator>; declare function castComparator(mapping: (data: TInput) => TOutput, compare?: Comparator | null, reverse?: boolean): Comparator; declare function castComparator(mapping: ComparatorMapping, compare?: null | undefined, reverse?: boolean): Comparator; declare function castComparator(mapping: TMapping, compare?: Comparator> | null, reverse?: boolean): Comparator>; /** * A value that describes how a comparator maps the input values to a * comparable value. * * @see https://radashi.js.org/reference/function/castComparator */ type ComparatorMapping = Mapping; /** * Cast the `mapping` value into a mapping function. * * - If `mapping` is a function, it's returned as is. * - If `mapping` is a property name, the mapping uses it to retrieve * the property value from a given object. * - If `mapping` is nullish, the mapping is `(input: T) => input`. * * @see https://radashi.js.org/reference/function/castMapping * @example * ```ts * const getName = castMapping('name') * const getFullName = castMapping(person => { * return `${person.firstName} ${person.lastName}` * }) * * getName({ name: 'John' }) // => 'John' * getFullName({ firstName: 'John', lastName: 'Doe' }) // => 'John Doe' * ``` * @version 12.2.0 */ declare function castMapping(mapping: TMapping): MappingFunction; /** * A value that can be casted with `castMapping`. * * @see https://radashi.js.org/reference/function/castMapping */ type Mapping = ((arg: T) => U) | CompatibleProperty; /** * A value that can be casted with `castMapping`. * * @see https://radashi.js.org/reference/function/castMapping */ type OptionalMapping = Mapping | null | undefined; /** * The input type of a mapping function created with `castMapping`. * * @see https://radashi.js.org/reference/function/castMapping */ type MappedInput = TMapping extends (arg: infer Arg) => any ? [Arg] extends [Any] ? unknown : Arg : TMapping extends keyof any ? { [P in TMapping]: TPropertyValue; } | (TMapping extends number ? readonly TPropertyValue[] : never) : unknown; /** * The return type of a mapping function created with `castMapping`. * * @see https://radashi.js.org/reference/function/castMapping */ type MappedOutput = TMapping extends (data: TInput) => infer Result ? [Result] extends [Any] ? unknown : Result : [TInput] extends [Any] ? unknown : TMapping extends null | undefined ? TInput : TMapping extends keyof TInput ? TInput[TMapping] : never; /** * A mapping function created with `castMapping`. * * @see https://radashi.js.org/reference/function/castMapping */ type MappingFunction = >(input: TInput) => MappedOutput; /** * A function that returns the value passed to it. * * @see https://radashi.js.org/reference/function/identity * @example * ```ts * identity() // => undefined * identity(1) // => 1 * identity("a") // => "a" * ``` * @version 12.7.0 */ declare function identity(): undefined; declare function identity(value: T): T; /** * A callback that does nothing and returns undefined. * * @example * ```ts * noop() // => undefined * noop(1) // => undefined * noop(1, 2, 3) // => undefined * ``` * @version 12.2.0 */ declare function noop(): undefined; /** * The `clamp` function restricts a number to be within a specified * range. * * - It takes three arguments: the number to clamp, the minimum value, * and the maximum value. * - If the number is less than the minimum, it returns the minimum. * - If the number is greater than the maximum, it returns the * maximum. * - Otherwise, it returns the number itself. * * @see https://radashi.js.org/reference/number/clamp * @example * ```ts * clamp(5, 1, 10) // returns 5 * clamp(0, 1, 10) // returns 1 * clamp(15, 1, 10) // returns 10 * ``` * @version 12.2.0 */ declare function clamp(n: number, min: number | null | undefined, max: number | null | undefined): number; /** * Checks if the given number is between zero (0) and the ending * number. 0 is inclusive. * * * Numbers can be negative or positive. * * Ending number is exclusive. * * @see https://radashi.js.org/reference/number/inRange * @example * ```ts * inRange(5, 10) // => true * inRange(-1, 10) // => false * inRange(10, 10) // => false * ``` * @version 12.1.0 */ declare function inRange(number: number, end: number): boolean; /** * Checks if the given number is between two numbers. * * * Numbers can be negative or positive. * * Starting number is inclusive. * * Ending number is exclusive. * * The start and the end of the range can be ascending OR descending * order. * * @see https://radashi.js.org/reference/number/inRange * @example * ```ts * inRange(5, 0, 10) // => true * inRange(-1, 0, 10) // => false * inRange(10, 0, 10) // => false * ``` */ declare function inRange(number: number, start: number, end: number): boolean; /** * Linearly interpolates between two numbers. * * @see https://radashi.js.org/reference/number/lerp * @example * ``` * lerp(0, 10, 0.5) // => 5 * lerp(5, 15, 0.2) // => 7 * lerp(-10, 10, 0.75) // => 5 * ``` * @version 12.2.0 */ declare function lerp(from: number, to: number, amount: number): number; /** * Max gets the greatest value from a list. * * @see https://radashi.js.org/reference/array/max * @example * ```ts * max([2, 3, 5]) // => 5 * max([{ num: 1 }, { num: 2 }], x => x.num) // => { num: 2 } * ``` * @version 12.1.0 */ declare function max(array: readonly [number, ...number[]]): number; declare function max(array: readonly number[]): number | null; declare function max(array: readonly [T, ...T[]], getter: (item: T) => number): T; declare function max(array: readonly T[], getter: (item: T) => number): T | null; /** * Min gets the smallest value from a list. * * @see https://radashi.js.org/reference/array/min * @example * ```ts * min([1, 2, 3, 4]) // => 1 * min([{ num: 1 }, { num: 2 }], x => x.num) // => { num: 1 } * ``` * @version 12.1.0 */ declare function min(array: readonly [number, ...number[]]): number; declare function min(array: readonly number[]): number | null; declare function min(array: readonly [T, ...T[]], getter: (item: T) => number): T; declare function min(array: readonly T[], getter: (item: T) => number): T | null; /** * Parse a duration string into a number. * * By default, the following units are supported: * - `week` * - `day` * - `hour` * - `minute` * - `second` * - `millisecond` * * By default, months and years are not supported, since these aren't * likely to be useful in the majority of cases and they introduce * ambiguity due to leap years and length differences between months. * * @see https://radashi.js.org/reference/number/parseDuration * @version 12.6.0 */ declare function parseDuration(duration: DurationString): number; declare function parseDuration(duration: NoInfer>, options: DurationParser.Options): number; /** * Parse a quantity string into its numeric value. You must provide a * unit conversion map. * * Note that {@link parseDuration `parseDuration`} also exists, which * can be used to parse duration strings (like `1d` or `1 day`). * * @see https://radashi.js.org/reference/number/parseQuantity * @version 12.6.0 */ declare function parseQuantity(quantity: QuantityString, options: QuantityParser.Options): number; /** * Creates a generator that will produce an iteration through the * range of numbers as requested. For nonempty ranges, the step must * be greater than zero. Zero and negative steps throw a RangeError * when iteration begins. * * @see https://radashi.js.org/reference/number/range * @example * ```ts * range(3) // yields 0, 1, 2, 3 * range(0, 3) // yields 0, 1, 2, 3 * range(0, 3, 'y') // yields y, y, y, y * range(0, 3, () => 'y') // yields y, y, y, y * range(0, 3, i => i) // yields 0, 1, 2, 3 * range(0, 3, i => `y${i}`) // yields y0, y1, y2, y3 * range(0, 3, obj) // yields obj, obj, obj, obj * range(0, 6, i => i, 2) // yields 0, 2, 4, 6 * ``` * @version 12.1.0 */ declare function range(startOrLength: number, end?: number, valueOrMapper?: T | ((i: number) => T), step?: number): Generator; /** * Rounds a number to the given precision. The default `precision` is * zero. An optional rounding function (e.g. `Math.floor` or * `Math.ceil`) can be provided. * * The `precision` argument is limited to be within the range of -323 * to +292. Without this limit, precision values outside this range * can result in NaN. * With nonzero precision, negative zero may be returned as positive zero. * * @see https://radashi.js.org/reference/number/round * @example * ```ts * round(123.456) * // => 123 * * round(1234.56, -2) * // => 1200 * * round(1234.56, 1, Math.floor) * // => 1234.5 * * round(1234.54, 1, Math.ceil) * // => 1234.6 * ``` * @version 12.2.0 */ declare function round(value: number, precision?: number, toInteger?: (value: number) => number): number; /** * Add up numbers related to an array in 1 of 2 ways: * 1. Sum all numbers in an array of numbers * 2. Sum all numbers returned by a callback function that maps * each item in an array to a number. * * @see https://radashi.js.org/reference/array/sum * @example * ```ts * sum([1, 2, 3]) * // => 6 * * sum([ * {value: 1}, * {value: 2}, * {value: 3} * ], (item) => item.value) * // => 6 * * sum([true, false, true], (item) => item ? 1 : 0) * // => 2 * ``` * @version 12.1.0 */ declare function sum(array: readonly number[]): number; declare function sum(array: readonly T[], fn: (item: T) => number): number; /** * Combines `Number.parseFloat` with NaN handling. By default, a zero * (0) is returned in place of NaN. * * @see https://radashi.js.org/reference/number/toFloat * @example * ```ts * toFloat("1.23") // => 1.23 * toFloat("foo") // => 0 * toFloat("1.23px", 1) // => 1.23 * toFloat("foo", 1) // => 1 * ``` * @version 12.1.0 */ declare function toFloat(value: unknown): number; declare function toFloat(value: unknown, defaultValue: T | undefined): number | T; /** * Combines `Number.parseInt` with NaN handling. By default, a zero * (0) is returned in place of NaN. * * @see https://radashi.js.org/reference/number/toInt * @example * ```ts * toInt("1.23") // => 1 * toInt("foo") // => 0 * toInt("1.23px", 1) // => 1 * toInt("foo", -1) // => -1 * ``` * @version 12.1.0 */ declare function toInt(value: unknown): number; declare function toInt(value: unknown, defaultValue: T | undefined): number | T; /** * Create a copy of the first object, and then merge the second object * into it recursively. Only plain objects are recursively merged. * * @see https://radashi.js.org/reference/object/assign * @example * ```ts * const a = { a: 0, b: 2, p: { a: 4 } } * const b = { a: 1, c: 3, p: { b: 5 } } * * assign(a, b) * // => { a: 1, b: 2, c: 3, p: { a: 4, b: 5 } } * ``` * @version 12.1.0 */ declare function assign, TOverride extends Record>(initial: TInitial, override: TOverride): Assign; /** * The return type for `assign`. * * It recursively merges object types that are not native objects. The * root objects are always merged. * * @see https://radashi.js.org/reference/object/assign */ type Assign = TInitial extends any ? TOverride extends any ? SimplifyMutable & Omit & AssignShared> : never : never; type AssignShared>, RequiredOverride = RequiredKeys>> = { [K in Shared & (RequiredInitial | RequiredOverride)]: AssignDeep; } & { [K in Exclude]?: AssignDeep; }; /** * Mimic the `Simplify` type and also remove `readonly` modifiers. */ type SimplifyMutable = {} & { -readonly [P in keyof T]: T[P]; }; /** * This represents a value that should only be replaced if it exists * as an initial value; never deeply assigned into. */ type AtomicValue = BuiltInType | CustomClass | BoxedPrimitive; /** * Handle mixed types when merging nested plain objects. * * For example, if the type `TOverride` includes both `string` and `{ n: * number }` in a union, `AssignDeep` will treat `string` as * unmergeable and `{ n: number }` as mergeable. */ type AssignDeep = never /** * When a native type is found in TInitial, it will only exist in * the result type if the override is optional. */ | (TInitial extends AtomicValue ? IsOptional extends true ? TInitial : never : never) /** * When a native type is found in TOverride, it will always exists * in the result type. */ | (TOverride extends AtomicValue ? TOverride : never) /** * Deep assignment is handled in this branch. * * 1. Exclude any native types from TInitial and TOverride * 2. If a non-native object type is not found in TInitial, simply * replace TInitial (or use "A | B" if the override is optional) * 3. For each non-native object type in TOverride, deep assign to * every non-native object in TInitial * 4. For each non-object type in TOverride, simply replace TInitial * (or use "A | B" if the override is optional) */ | (Exclude extends infer TOverride ? Exclude> extends infer TInitial ? [Extract] extends [never] ? TOverride | (IsOptional extends true ? TInitial : never) : TInitial extends object ? TOverride extends object ? IsExactType extends true ? TOverride : Assign : // 4. TOverride | (IsOptional extends true ? TInitial : never) : Extract | (IsOptional extends true ? TInitial : never) : never : never); /** * Creates a shallow copy of the given object/value. * * @see https://radashi.js.org/reference/object/clone * @example * ```ts * const original = { a: 1, b: { c: 3 } } * const cloned = clone(original) * // => { a: 1, b: { c: 3 } } * original !== cloned * // => true * original.b === cloned.b * // => true * ``` * @version 12.1.0 */ declare function clone(obj: T): T; /** * A strategy for cloning objects with `cloneDeep`. * * Methods **must** call the `track` function with the new parent * object **before** looping over the input object's * properties/elements for cloning purposes. This protects against * circular references. * * Methods may return the input object to indicate that cloning should * be skipped. * * Methods may return null to indicate that the default cloning logic * should be used. * @version 12.2.0 */ interface CloningStrategy { cloneMap: (parent: Map, track: (newParent: Map) => Map, clone: (value: T) => T) => Map | null; cloneSet: (parent: Set, track: (newParent: Set) => Set, clone: (value: T) => T) => Set | null; cloneArray: (parent: readonly T[], track: (newParent: T[]) => T[], clone: (value: T) => T) => T[] | null; cloneObject: (parent: T, track: (newParent: T) => T, clone: (value: T) => T) => T | null; cloneOther: (parent: T, track: (newParent: T) => T, clone: (value: T) => T) => T | null; } declare const DefaultCloningStrategy: CloningStrategy; /** * If you don't need support for non-enumerable properties or computed * properties, and you're not using custom classes, you can use this * strategy for better performance. */ declare const FastCloningStrategy: { cloneObject: (input: T, track: (newParent: T) => T, clone: (value: T_1) => T_1) => T; }; /** * Clone the given object and possibly other objects nested inside. * * By default, the only objects that get cloned are plain objects, * non-native class instances, arrays, `Set` instances, and `Map` * instances. If an object is not cloned, any objects nested inside * are also not cloned. * * You may define a custom cloning strategy by passing a partial * implementation of the `CloningStrategy` interface to the * `cloneDeep` function. Any undefined methods will fall back to the * default cloning logic. Your own methods may return null to indicate * that the default cloning logic should be used. They may also return * the input object to indicate that cloning should be skipped. * * ```ts * const obj = { a: 1, b: { c: 2 } } * const clone = cloneDeep(obj) * * assert(clone !== obj) * assert(clone.b !== obj.b) * assert(JSON.stringify(clone) === JSON.stringify(obj)) * ``` */ declare function cloneDeep(root: T, customStrategy?: Partial): T; /** * The opposite of crush, given an object that was crushed into key * paths and values will return the original object reconstructed. * * @see https://radashi.js.org/reference/object/construct * @example * ```ts * construct({ name: 'ra', 'children.0.name': 'hathor' }) * // { name: 'ra', children: [{ name: 'hathor' }] } * ``` * @version 12.1.0 */ declare function construct(obj: TObject): object; /** * Flattens a deep object to a single dimension, converting the keys * to dot notation. * * @see https://radashi.js.org/reference/object/crush * @example * ```ts * crush({ name: 'ra', children: [{ name: 'hathor' }] }) * // { name: 'ra', 'children.0.name': 'hathor' } * ``` * @version 12.1.0 */ declare function crush(value: T): Crush; /** * The return type of the `crush` function. * * This type is limited by TypeScript's development. There's no * reliable way to detect if an object will pass `isObject` or not, so * we cannot infer the property types of nested objects that have been * crushed. * * @see https://radashi.js.org/reference/object/crush */ type Crush = T extends readonly (infer U)[] ? Record : Simplify] extends [never] ? never : Record) | ([Exclude] extends [never] ? never : [Extract] extends [never] ? { [P in Prop]: Value; } : Record) : never : never : never>>; type KeyOf = object extends T ? keyof any : keyof T; type ValueOf = object extends T ? unknown : T[keyof T]; type KeyFilterFunction = (value: ValueOf, key: KeyOf, obj: T) => boolean; /** * Functions can use this type to accept either an array of keys or a * filter function. * @version 12.2.0 */ type KeyFilter = KeyFilterFunction | readonly Key[]; /** * Extract the keys of an object that pass a filter. */ type FilteredKeys | null | undefined> = Extract; /** * Returns true if the key is in the “keys array” or if the “filter * function” returns true. This function is useful when creating other * functions that need to enumerate an object or array and filter keys * in a flexible manner. Using it directly in everyday code is not * recommended. * * @see https://radashi.js.org/reference/object/filterKey * @example * ```ts * const a = { a: 1, b: 2, c: 3 } * filterKey(a, 'a', ['a', 'b']) * // => true * filterKey(a, 'a', ['a', 'b']) * // => true * ``` */ declare function filterKey(obj: T, key: keyof T, filter: KeyFilter | null | undefined): boolean; declare function filterKey(obj: object, key: keyof any, filter: KeyFilter | null | undefined): boolean; /** * Dynamically get a nested value from an array or object with a * string. * * @see https://radashi.js.org/reference/object/get * @example * ```ts * const person = { * name: 'John', * friends: [{ name: 'Jane' }] * } * * get(person, 'friends[0].name') * // => 'Jane' * ``` * @version 12.1.0 */ declare function get(value: any, path: string, defaultValue?: TDefault): TDefault; /** * Returns a map entry or stores and returns the provided value when missing. * * @see https://radashi.js.org/reference/object/getOrInsert * @example * ```ts * const counts = new Map() * * getOrInsert(counts, 'clicks', 1) * getOrInsert(counts, 'clicks', 5) * // => 1 * ``` * @version 12.7.0 */ declare function getOrInsert(map: Map, key: K, value: V): V; declare function getOrInsert(map: Map | WeakMap, key: K, value: V): V; /** * Returns a map entry or stores the computed value when the key is missing. * * @see https://radashi.js.org/reference/object/getOrInsertComputed * @example * ```ts * const counts = new Map() * * getOrInsertComputed(counts, 'clicks', () => 1) * getOrInsertComputed(counts, 'clicks', () => 5) * // => 1 * ``` * @version 12.7.0 */ declare function getOrInsertComputed(map: Map, key: K, factory: () => V): V; declare function getOrInsertComputed(map: Map | WeakMap, key: K, compute: () => V): V; /** * Returns a new object whose keys are the values of the given object * and its values are the keys of the given object. * * @see https://radashi.js.org/reference/object/invert * @example * ```ts * const a = { a: 1, b: 2, c: 3 } * invert(a) * // => { 1: 'a', 2: 'b', 3: 'c' } * ``` * @version 12.1.0 */ declare function invert(obj: Record): Record; /** * Check if a property key is “dangerous” in the sense that it could * be used to modify built-in objects, possibly leading to prototype * pollution or other unintended side effects. * * If you pass an object, it will be checked for a `null` prototype, * in which case, the key will be considered safe. * * @see https://radashi.js.org/reference/object/isDangerousKey * @version 12.5.1 */ declare function isDangerousKey(key: PropertyKey, object?: object): boolean; /** * Get a string list of all key names that exist in an object (deep). * * @see https://radashi.js.org/reference/object/keys * @example * ```ts * keys({ name: 'ra' }) // ['name'] * * keys({ name: 'ra', children: [{ name: 'hathor' }] }) * // ['name', 'children.0.name'] * ``` * @version 12.1.0 */ declare function keys(value: object): string[]; /** * Convert an object to a list, mapping each entry into a list item. * * @see https://radashi.js.org/reference/object/listify * @example * ```ts * const a = { a: 1, b: 2, c: 3 } * listify(a, (key, value) => ({ key, value })) * // => [ * // { key: 'a', value: 1 }, * // { key: 'b', value: 2 }, * // { key: 'c', value: 3 } * // ] * ``` * @version 12.1.0 */ declare function listify(obj: Record, toItem: (key: Key, value: Value) => Item): Item[]; type LowercaseKeys> = { [P in keyof T & string as Lowercase

]: T[P]; }; /** * Convert all keys in an object to lower case. * * @see https://radashi.js.org/reference/object/lowerize * @example * ```ts * const a = { A: 1, B: 2, C: 3 } * lowerize(a) * // => { a: 1, b: 2, c: 3 } * ``` * @version 12.1.0 */ declare function lowerize>(obj: T): LowercaseKeys; /** * Map over all the keys to create a new object. * * @see https://radashi.js.org/reference/object/mapEntries * @example * ```ts * const a = { a: 1, b: 2, c: 3 } * mapEntries(a, (key, value) => [value, key]) * // => { 1: 'a', 2: 'b', 3: 'c' } * ``` * @version 12.1.0 */ declare function mapEntries(obj: Record, toEntry: (key: TKey, value: TValue) => [TNewKey, TNewValue]): Record; /** * Map over the own enumerable string and symbol keys of an object * to return a new object. * * @see https://radashi.js.org/reference/object/mapKeys * @example * ```ts * const a = { a: 1, b: 2, c: 3 } * mapKeys(a, (key, value) => key + value) * // => { a1: 1, b2: 2, c3: 3 } * ``` * @version 12.1.0 */ declare function mapKeys(obj: Record, mapFunc: (key: TKey, value: TValue) => TNewKey): Record; /** * Map over all the keys to create a new object. * * @see https://radashi.js.org/reference/object/mapValues * @example * ```ts * const a = { a: 1, b: 2, c: 3 } * mapValues(a, (value, key) => value * 2) * // => { a: 2, b: 4, c: 6 } * ``` * @version 12.1.0 */ declare function mapValues(obj: T, mapFunc: (value: Required[keyof T], key: keyof T) => U): { [K in keyof T]: U; }; /** * Merges two option objects into a new object. * - If both arguments are defined, properties * from the second object (`b`) will override those * from the first one (`a`) when keys overlap * - If either argument is `undefined`, the other is returned * - If both are `undefined`, the result is `undefined` * * @param a - The first options object, or `undefined`. * @param b - The second options object, or `undefined`. * @returns A merged object when both arguments are defined, otherwise the defined argument, or `undefined` if both are `undefined`. * @version 12.9.0 * * @see https://radashi.js.org/reference/object/mergeOptions * * @example * ```ts * // Merging two objects with overlapping keys * mergeOptions({ a: 1, b: 2 }, { b: 3, c: 4 }) * // => { a: 1, b: 3, c: 4 } * * // First argument undefined * mergeOptions(undefined, { a: 1 }) * // => { a: 1 } * * // Second argument undefined * mergeOptions({ a: 1 }, undefined) * // => { a: 1 } * * // Both arguments undefined * mergeOptions(undefined, undefined) * // => undefined * ``` */ declare function mergeOptions(a: A, b: B): MergeOptions; /** * Computes the merged type of two option objects, handling `undefined` and partials. * * @version 12.9.0 */ type MergeOptions = (undefined extends A ? B : never) | (undefined extends B ? NonNullable : never) | MergePresent, NonNullable>; type Expand = T extends object ? { [K in keyof T]: Expand; } : T; type MergePresent = [A, B] extends [never, never] ? never : A extends object ? B extends object ? Expand> : never : never; type MergeObjects = { [K in MergeRequiredKeys]: MergeValue; } & { [K in MergeOptionalKeys]?: MergeValue; }; type MergeRequiredKeys = RequiredKeys | Exclude, keyof B> | (RequiredKeys & OptionalKeys); type MergeOptionalKeys = Exclude, keyof B> | Exclude, RequiredKeys>; type MergeValue = K extends keyof B ? K extends OptionalKeys ? K extends keyof A ? PropValue | PropValue : PropValue : B[K] : K extends keyof A ? PropValue : never; type PropValue = K extends OptionalKeys ? Required>[K] : T[K]; /** * Omit a list of properties from an object returning a new object * with the properties that remain. * * @see https://radashi.js.org/reference/object/omit * @example * ```ts * const a = { a: 1, b: 2, c: 3 } * omit(a, ['b']) * // => { a: 1, c: 3 } * ``` * @version 12.1.0 */ declare function omit(obj: T, keys: readonly TKeys[]): Omit; /** * Pick a list of properties from an object into a new object. * * ⚠️ When used with a predicate function, `pick` is potentially * unsafe, because of partial type matching performed by TypeScript. * If you pass an object with more properties than its TypeScript type * has listed, the `value` and `key` parameter types of your callback * will be inaccurate. * * @see https://radashi.js.org/reference/object/pick * @example * ```ts * const a = { a: 1, b: 2, c: 3 } * * pick(a, ['a', 'c']) * // => { a: 1, c: 3 } * * pick(a, (value, key) => value > 1) * // => { b: 2, c: 3 } * ``` * @version 12.1.0 */ declare function pick>(obj: T, filter: F): Pick>; /** * Opposite of get, dynamically set a nested value into an object * using a key path. Does not modify the given initial object. * Primitive intermediates are replaced with objects or arrays when * a property needs to change. * * @see https://radashi.js.org/reference/object/set * @example * ```ts * set({}, 'name', 'ra') // => { name: 'ra' } * set({}, 'cards[0].value', 2) // => { cards: [{ value: 2 }] } * ``` * @version 12.1.0 */ declare function set(initial: T, path: string, value: K): T; /** * Removes (shakes out) undefined entries from an object. Optional * second argument shakes out values by custom evaluation. * * Note that non-enumerable keys are never shaken out. * * @see https://radashi.js.org/reference/object/shake * @example * ```ts * const a = { a: 1, b: undefined, c: 3 } * shake(a) * // => { a: 1, c: 3 } * ``` * @version 12.1.0 */ declare function shake(obj: T): { [K in keyof T]: Exclude; }; declare function shake(obj: T, filter: ((value: unknown) => boolean) | undefined): T; interface TraverseOptions { /** * A function that returns the keys of the object to be traversed. * * @default Object.keys */ ownKeys?: ((parent: object) => Iterable) | null; /** * When true, the visitor callback will be invoked for the root object. * * @default false */ rootNeedsVisit?: boolean | null; } /** * Recursively visit each property of an object (or each element of an * array) and its nested objects or arrays. By default, the only * nested objects to be traversed are plain objects and arrays. * * @see https://radashi.js.org/reference/object/traverse * @example * ```ts * import { traverse } from 'radashi' * * const root = { a: 1, b: { c: { d: [2] }, e: 3 } } * * traverse(root, (value, key, parent, context) => { * console.log(key, '=>', value) * }) * // Logs the following: * // a => 1 * // b => { … } * // c => { … } * // d => [ 2 ] * // 0 => 2 * // e => 3 * ``` * @version 12.2.0 */ declare function traverse(root: object, visitor: TraverseVisitor, options?: (TraverseOptions & { rootNeedsVisit?: null; }) | null, outerContext?: TraverseContext): boolean; declare function traverse(root: object, visitor: TraverseVisitor, options?: TraverseOptions | null, outerContext?: TraverseContext): boolean; /** * The visitor callback for the `traverse` function. */ type TraverseVisitor = (value: unknown, key: Key, parent: object, context: TraverseContext, options: TraverseOptions & { rootNeedsVisit?: null; }) => (() => boolean | void) | boolean | void; /** * The context object for the `traverse` function. */ interface TraverseContext { /** * The current value being traversed. */ readonly value: unknown; /** * The property key or index with which the current value was found. */ readonly key: Key; /** * The parent object of the current value. */ readonly parent: object; /** * The stack of parent objects. The last object is the current * parent. * * ⚠️ This array must not be mutated directly or referenced outside * the `visitor` callback. If that's necessary, you'll want to clone * it first. */ readonly parents: readonly object[]; /** * The path to the `parent` object. The last key is the current key. * * ⚠️ This array must not be mutated directly or referenced outside * the `visitor` callback. If that's necessary, you'll want to clone * it first. */ readonly path: readonly (keyof any)[]; /** * When the current value is a traversable object/iterable, this * function can be used to skip traversing it altogether. * * If the `obj` argument is provided, it marks the given object as * skipped (instead of the current value), preventing it from being * traversed. */ readonly skip: (obj?: object) => void; readonly skipped: ReadonlySet; } type UppercaseKeys> = { [P in keyof T & string as Uppercase

]: T[P]; }; /** * Convert all keys in an object to upper case. * * @see https://radashi.js.org/reference/object/upperize * @example * ```ts * const a = { a: 1, b: 2, c: 3 } * upperize(a) * // => { A: 1, B: 2, C: 3 } * ``` * @version 12.1.0 */ declare function upperize>(obj: T): UppercaseKeys; interface AggregateError extends Error { errors: any[]; cause?: unknown; } interface AggregateErrorConstructor { new (errors: Iterable, message?: string, options?: { cause?: unknown; }): AggregateError; (errors: Iterable, message?: string, options?: { cause?: unknown; }): 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. * The polyfill copies the iterable of errors and supports an optional * message and `options.cause`, like the native constructor. * * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AggregateError * @version 12.2.0 */ declare const AggregateErrorOrPolyfill: AggregateErrorConstructor; /** * A human-readable quantity string. */ type QuantityString = `1 ${Unit}` | `${number} ${Unit}s` | `${number}${ShortUnit}`; /** * Parses a quantity string into its numeric value. * * You can use `parseQuantity` instead for a light wrapper that * doesn't require the `new` keyword. * * See {@link parseQuantity `parseQuantity`} for more information. * * @version 12.6.0 */ declare class QuantityParser { private units; private short?; constructor({ units, short }: QuantityParser.Options); /** * Parse a quantity string into its numeric value * * @throws {Error} If the quantity string is invalid or contains an unknown unit */ parse(quantity: QuantityString): number; } declare namespace QuantityParser { /** * The options for a `QuantityParser` instance. */ type Options = { units: Record; short?: Record; }; /** * Convert a `QuantityParser` instance to a human-readable quantity string. */ type ToString> = T extends QuantityParser ? QuantityString : never; } /** * The default duration units supported by `DurationParser`. */ type DurationUnit = keyof typeof DurationParser.units; /** * The default aliases for `DurationUnit`. */ type DurationShortUnit = keyof typeof DurationParser.shortUnits; /** * A human-readable duration string. */ type DurationString = QuantityString; declare const DURATION_UNITS: { readonly week: 604800000; readonly day: 86400000; readonly hour: 3600000; readonly minute: 60000; readonly second: 1000; readonly millisecond: 1; }; declare const DURATION_SHORT_UNITS: { readonly w: "week"; readonly d: "day"; readonly h: "hour"; readonly m: "minute"; readonly s: "second"; readonly ms: "millisecond"; }; /** * Parses a duration string into its numeric value. * * You can use `parseDuration` instead for a light wrapper that * doesn't require the `new` keyword. * * See {@link parseDuration `parseDuration`} for more information. * * @version 12.6.0 */ declare class DurationParser extends QuantityParser { constructor(options?: DurationParser.Options); static get units(): typeof DURATION_UNITS; static get shortUnits(): typeof DURATION_SHORT_UNITS; } declare namespace DurationParser { /** * The options for a `DurationParser` instance. */ type Options = { units?: Record; short?: Record; }; } interface AbortSignal { aborted?: boolean; reason?: unknown; addEventListener(type: 'abort', listener: () => void): void; removeEventListener(type: 'abort', listener: () => void): void; } /** * A permit that can be acquired from a {@link Semaphore}. */ declare class SemaphorePermit { readonly semaphore: Semaphore; readonly request: PromiseWithResolvers; readonly weight: number; constructor(semaphore: Semaphore, request: PromiseWithResolvers, weight: number); /** * Releases this permit back to the semaphore, allowing another * operation to acquire it. */ release(): void; } /** * Options for acquiring a permit from a semaphore. */ type SemaphoreAcquireOptions = { signal?: AbortSignal; weight?: number; }; /** * Implements a counting semaphore that controls access to a limited * resource. Useful for limiting concurrent operations or access to * constrained resources. * * @see https://radashi.js.org/reference/oop/Semaphore * @version 12.6.0 */ declare class Semaphore { readonly maxCapacity: number; protected queue: SemaphorePermit[]; /** * Current number of permits available to be acquired */ readonly capacity: number; /** * Number of pending acquisition requests. */ get queueLength(): number; /** * Creates a new semaphore with the specified capacity. * @param maxCapacity Maximum number of permits that can be issued simultaneously */ constructor(maxCapacity: number); /** * Acquires a permit from this semaphore, waiting if necessary until * one becomes available. * @param options.signal - The signal to abort the acquisition * @param options.weight - The weight of the permit to acquire * @returns A promise that resolves to a permit when one is * available */ acquire({ signal, weight, }?: SemaphoreAcquireOptions): Promise; /** * Rejects all pending acquisition requests. */ reject(error: Error): void; /** * Releases a permit back to the semaphore, increasing capacity and * potentially fulfilling a pending acquisition request. */ protected release(permit: SemaphorePermit): void; } declare class TimeoutError extends Error { name: string; constructor(message?: string); } /** * Returns a value randomly jittered by an absolute offset. * * @see https://radashi.js.org/reference/random/absoluteJitter * @example * ```ts * const result = absoluteJitter(100, 5) * result >= 95 && result <= 105 * // => true * ``` * @version 12.7.0 */ declare function absoluteJitter(base: number, offset: number): number; /** * “Draw” a random item from an array. The item is not removed from * the array. Returns `null` if the array is empty. * * @see https://radashi.js.org/reference/random/draw * @example * ```ts * const numbers = [1, 2, 3] * * draw(numbers) * // => 2 * numbers * // => [1, 2, 3] * ``` * @version 12.1.0 */ declare function draw(array: T): T extends readonly [any, ...any[]] ? T[number] : T[number] | null; /** * Returns a value randomly jittered by a proportion of the base value. * * @see https://radashi.js.org/reference/random/proportionalJitter * @example * ```ts * const result = proportionalJitter(100, 0.25) * result >= 75 && result <= 125 * // => true * ``` * @version 12.7.0 */ declare function proportionalJitter(base: number, factor: number): number; /** * Generates a random integer between min and max. Both min and max * are inclusive. * * @see https://radashi.js.org/reference/random/random * @example * ```ts * random(1, 10) * // => 5 * ``` * @version 12.1.0 */ declare function random(min: number, max: number): number; /** * Create a new array with the items of the given array but in a random order. * The randomization is done using the [Fisher-Yates algorithm](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle), * which is mathematically proven to be unbiased (i.e. all permutations are equally likely). * * @see https://radashi.js.org/reference/random/shuffle * @example * ```ts * const numbers = [1, 2, 3, 4, 5] * const shuffled = shuffle(numbers) * // => [2, 1, 4, 5, 3] * shuffled !== numbers * // => true * ``` * @version 12.1.0 */ declare function shuffle( /** * The array to shuffle. */ array: readonly T[], /** * You can provide a custom random function to make the shuffle more or less * random. The custom random function takes minimum and maximum values and * returns a random number between them. * * @default _.random * @example * * ```ts * const array = [1, 2, 3, 4, 5] * const customRandom = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min * _.shuffle(array, customRandom) * ``` */ random?: (min: number, max: number) => number): T[]; /** * Generate a random string of a given length. * * @see https://radashi.js.org/reference/random/uid * @example * ```ts * uid(8) * // => "a3fSDf32" * ``` * @version 12.1.0 */ declare function uid(length: number, specials?: string): string; interface Series { min: (a: T, b: T) => T; max: (a: T, b: T) => T; first: () => T; last: () => T; next: (current: T, defaultValue?: T) => T; previous: (current: T, defaultValue?: T) => T; spin: (current: T, num: number) => T; } /** * Creates a series object around a list of values that should be * treated with order. * * @see https://radashi.js.org/reference/series/series * @example * ```ts * const numbers = series([1, 2, 3]) * * numbers.first() // => 1 * numbers.last() // => 3 * numbers.next(2) // => 3 * numbers.previous(2) // => 1 * numbers.spin(2, 1) // => 3 * numbers.spin(2, -1) // => 1 * ``` * @version 12.1.0 */ declare const series: (items: readonly T[], toKey?: (item: T) => string | symbol) => Series; /** * Formats the given string in camel case fashion. * * @see https://radashi.js.org/reference/string/camel * @example * ```ts * camel('hello world') // => 'helloWorld' * camel('one two-THREE') // => 'oneTwoThree' * camel('helloWorld') // => 'helloWorld' * ``` * @version 12.1.0 */ declare function camel(str: string): string; /** * Capitalize the first word of the string. * * @see https://radashi.js.org/reference/string/capitalize * @example * ```ts * capitalize('hello') // => 'Hello' * capitalize('one two three') // => 'One two three' * ``` * @version 12.1.0 */ declare function capitalize(str: string): string; /** * Formats the given string in dash case fashion. * * @see https://radashi.js.org/reference/string/dash * @example * ```ts * dash('hello world') // => 'hello-world' * dash('one two_THREE') // => 'one-two-three' * dash('helloWord') // => 'hello-word' * ``` * @version 12.1.0 */ declare function dash(str: string): string; /** * Removes accents and converts extended Latin ligatures to basic Latin text. * * @see https://radashi.js.org/reference/string/deburr * @example * ```ts * deburr('déjà vu') // => 'deja vu' * deburr('Ærøskøbing') // => 'Aeroskobing' * ``` * @version 12.8.0 */ declare function deburr(input: string): string; /** * Remove indentation from a string. The given string is expected to * be consistently indented (i.e. the leading whitespace of the first * non-empty line is the minimum required for all non-empty lines). * * If the `indent` argument is nullish, the indentation is detected * from the first non-empty line. Detection is cheap and robust for * most use cases, so you should only set an explicit `indent` if * necessary. * * @see https://radashi.js.org/reference/string/dedent * @example * ```ts * // This is indented with 4 spaces. * const input = ` * Hello * World * ` * * // Explicit indentation * dedent(input, ' ') * // => ' Hello\n World\n' * * // Detected indentation * dedent(input) * // => 'Hello\nWorld\n' * * // Tagged template strings * const str = dedent` * Foo ${1 + 1} * Bar ${2 * 2} * ` * // => 'Foo 2\nBar 4' * ``` * @version 12.3.0 */ declare function dedent(template: TemplateStringsArray, ...values: unknown[]): string; declare function dedent(text: string, indent?: string | null): string; /** * Escape HTML characters in a string. * * @see https://radashi.js.org/reference/string/escapeHTML * @example * ```ts * escapeHTML('

') * // => '<div>Hello, world!</div>' * ``` * @version 12.6.0 */ declare function escapeHTML(input: string): string; /** * Formats the given string in pascal case fashion. * * @see https://radashi.js.org/reference/string/pascal * @example * ```ts * pascal('hello world') // => 'HelloWorld' * pascal('va va boom') // => 'VaVaBoom' * pascal('helloWorld') // => 'HelloWorld' * ``` * @version 12.1.0 */ declare function pascal(str: string): string; /** * Calculate the similarity between two strings using the Levenshtein * distance algorithm. * * One thing to note is that the argument order is unimportant. The * algorithm will always return the same result regardless of the * order of the arguments. * * Adapted from * [@fabiospampinato/tiny-levenshtein](https://github.com/fabiospampinato/tiny-levenshtein) * with ❤️. * * @see https://radashi.js.org/reference/string/similarity * @example * ```ts * similarity('abc', 'abc') // 0 * similarity('a', 'b') // 1 * similarity('ab', 'ac') // 1 * similarity('ac', 'bc') // 1 * similarity('abc', 'axc') // 1 * similarity('kitten', 'sitting') // 3 * ``` * @version 12.2.0 */ declare function similarity(str1: string, str2: string): number; /** * Formats the given string in snake case fashion. * * @see https://radashi.js.org/reference/string/snake * @example * ```ts * snake('hello world') // => 'hello_world' * snake('one two-THREE') // => 'one_two_three' * snake('helloWorld') // => 'hello_world' * ``` * @version 12.1.0 */ declare function snake(str: string, options?: { splitOnNumber?: boolean; }): string; /** * Replace data by name in template strings. The default expression * looks for `{{name}}` to identify names. * * @see https://radashi.js.org/reference/string/template * @example * ```ts * template('Hello, {{name}}', { name: 'Radashi' }) * // "Hello, Radashi" * * template('Hello, ', { name: 'Radashi' }, /<(.+?)>/g) * // "Hello, Radashi" * ``` * @version 12.1.0 */ declare function template(str: string, data: Record, regex?: RegExp): string; /** * Formats the given string in title case fashion. * * @see https://radashi.js.org/reference/string/title * @example * ```ts * title('hello world') // => 'Hello World' * title('va_va_boom') // => 'Va Va Boom' * title('root-hook') // => 'Root Hook' * title('queryItems') // => 'Query Items' * ``` * @version 12.1.0 */ declare function title(str: string): string; /** * Trims all prefix and suffix characters from the given string. Like * the builtin trim function but accepts other characters you would * like to trim and trims multiple characters. * * @see https://radashi.js.org/reference/string/trim * @example * ```ts * trim(' hello ') // => 'hello' * trim('__hello__', '_') // => 'hello' * trim('/repos/:owner/:repo/', '/') // => 'repos/:owner/:repo' * trim('222222__hello__1111111', '12_') // => 'hello' * ``` * @version 12.1.0 */ declare function trim(str: string, charsToTrim: string): string; /** * Asserts that a condition is true. If the condition is false, an * error is thrown. This function uses TypeScript's `asserts` keyword * to narrow the type of the value being asserted. * * @see https://radashi.js.org/reference/typed/assert * @example * ```ts * function processValue(value: string | null) { * assert(value, 'Value cannot be null or an empty string') * // value is now narrowed to string * console.log(value.toUpperCase()) * } * * processValue('hello') // logs "HELLO" * processValue(null) // throws Error: Value cannot be null or an empty string * processValue('') // throws Error: Value cannot be null or an empty string * ``` * @example * ```ts * // Example with false literal, return type is never * const result = * status === 'success' * ? 1 * : status === 'pending' * ? 2 * : assert(false, 'Unexpected status') * * typeof result * // ^? 1 | 2 * ``` * @version 12.6.0 */ declare function assert(condition: false, error?: string | Error): never; declare function assert(condition: unknown, error?: string | Error): asserts condition; /** * Gets a readable message from an unknown error value. * * Empty error messages and unsupported values return `"Unknown error."`. * * @see https://radashi.js.org/reference/typed/getErrorMessage * @example * ```ts * getErrorMessage(new Error('Request failed')) // => 'Request failed' * getErrorMessage('Request failed') // => 'Request failed' * getErrorMessage(null) // => 'Unknown error.' * ``` * @version 12.8.0 */ declare function getErrorMessage(error: unknown): string; /** * Literally just `Array.isArray` but with better type inference. * * @see https://radashi.js.org/reference/typed/isArray * @example * ```ts * isArray([]) // => true * isArray('hello') // => false * ``` * @version 12.1.0 */ declare const isArray: (value: Input) => value is ExtractArray; /** * An absurdly complicated but accurate type for extracting Array types. * * It's like `Extract` but better with edge cases. */ type ExtractArray = T extends any ? [StrictExtract] extends [readonly any[]] ? Extract : [StrictExtract] extends [any[]] ? Extract : unknown[] extends T ? unknown[] : never : never; type AsyncIterable = globalThis.AsyncIterable; /** * Checks if a value is an async iterable. * * @see https://radashi.js.org/reference/typed/isAsyncIterable * @example * ```ts * isAsyncIterable((async function* () { yield 1 })()) * // => true * * isAsyncIterable([1, 2, 3]) * // => false * ``` * @version 12.4.0 */ declare function isAsyncIterable(value: unknown): value is AsyncIterable; /** * Return true if the give value is a BigInt. * * @see https://radashi.js.org/reference/typed/isBigInt * @example * ```ts * _.isBigInt(0n) // => true * _.isBigInt(BigInt(0)) // => true * _.isBigInt(12) // => false * _.isBigInt('0n') // => false * ``` * @version 12.4.0 */ declare function isBigInt(value: unknown): value is bigint; declare function isBoolean(value: unknown): value is boolean; /** * Checks if the given value is a class. This function verifies * if the value was defined using the `class` syntax. Old school * classes (defined with constructor functions) will return false. * "Native classes" like `Error` will also return false. * * @see https://radashi.js.org/reference/typed/isClass * @example * ```ts * isClass(class CustomClass {}) // => true * isClass('abc') // => false * isClass({}) // => false * ``` * @version 12.3.0 */ declare function isClass(value: T): value is ExtractClass; /** * Used by the `isClass` type guard. It handles type narrowing for * class constructors and even narrows `any` types. */ type ExtractClass = [StrictExtract] extends [Class] ? Extract : T extends any ? Class extends T ? Class : never : never; /** * Return true if the given value is a Date object. * * Instances from [other realms][1] are also supported. * * [1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof#instanceof_and_multiple_realms * * @see https://radashi.js.org/reference/typed/isDate * @example * ```ts * isDate(new Date()) // => true * isDate('hello') // => false * ``` * @version 12.1.0 */ declare function isDate(value: unknown): value is Date; /** * Return true if the given value is empty. * This function also uses [Type Guards](https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards) to ensure type safety * * Empty values include: * - `null` * - `undefined` * - `0` * - `0n` or `BigInt(0)` * - any boolean * - empty string * - empty array * - invalid `Date` time * - object with `length` property of `0` * - object with `size` property of `0` * - object with no enumerable keys * * @see https://radashi.js.org/reference/typed/isEmpty * @example * ```ts * isEmpty(0) // => true * isEmpty(null) // => true * isEmpty(undefined) // => true * isEmpty([]) // => true * isEmpty({}) // => true * ``` * @version 12.1.0 */ declare function isEmpty(value: T): value is ToEmpty; declare function isEmpty(value: unknown): boolean; type NeverEmpty = symbol | Function; /** * A type that can be narrowed by `isEmpty`. */ type ToEmptyAble = NeverEmpty | boolean | number | string | readonly any[] | null | undefined; /** * Narrow a type to an empty value. * * Due to TypeScript limitations, object types cannot be narrowed, * except for arrays and functions. */ type ToEmpty = (T extends any[] ? never[] : Extract) extends infer U ? Extract : never; /** * Return true if the given values are equal. * * To determine equality, `Object.is()` is used first. If it returns * false, we do the following special checks: * - `Date` and `Date` with the same time * - `RegExp` and `RegExp` with the same pattern/flags * - object with the same keys and values (recursive) * * @see https://radashi.js.org/reference/typed/isEqual * @example * ```ts * isEqual(0, 0) // => true * isEqual(0, 1) // => false * ``` * @version 12.1.0 */ declare function isEqual(x: TType, y: TType): boolean; /** * Return true if the given value is an Error object. * * Instances from [other realms][1] are also supported. * * [1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof#instanceof_and_multiple_realms * * @see https://radashi.js.org/reference/typed/isError * @example * ```ts * isError(new Error()) // => true * isError('hello') // => false * ``` * @version 12.2.0 */ declare function isError(value: unknown): value is Error; /** * Return true if the given value is a non-integer number, including * Infinity and -Infinity. Return false for integers, NaN, and * non-number values. * * @see https://radashi.js.org/reference/typed/isFloat * @example * ```ts * isFloat(0) // => false * isFloat(0.1) // => true * isFloat(Infinity) // => true * isFloat(-Infinity) // => true * isFloat(NaN) // => false * ``` * @version 12.1.0 */ declare function isFloat(value: any): value is number; /** * Return true if the given value is a function. * * @see https://radashi.js.org/reference/typed/isFunction * @example * ```ts * isFunction(0) // => false * isFunction(() => {}) // => true * isFunction(function() {}) // => true * isFunction(async function() {}) // => true * isFunction(class {}) // => false * ``` * @version 12.1.0 */ declare function isFunction(value: any): value is Function; /** * Literally just `Number.isInteger` with a better type. * * @see https://radashi.js.org/reference/typed/isInt * @example * ```ts * isInt(0) // => true * isInt(0.1) // => false * ``` * @version 12.1.0 */ declare const isInt: (value: unknown) => value is number; /** * Return true if the given value is a string that can be parsed as an * integer. * * @see https://radashi.js.org/reference/typed/isIntString * @example * ```ts * isIntString('0') // => true * isIntString('0.1') // => false * isIntString('+1') // => false * ``` * @version 12.2.0 */ declare function isIntString(value: any): value is `${number}`; declare function isIterable(value: unknown): value is Iterable; /** * Return true if the given value is a Map. * * Instances from [other realms][1] are also supported. * * [1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof#instanceof_and_multiple_realms * * @see https://radashi.js.org/reference/typed/isMap * @example * ```ts * isMap(new Map()) // => true * isMap(new Set()) // => false * ``` * @version 12.2.0 */ declare function isMap(value: Input): value is ExtractMap; /** * An absurdly complicated but accurate type for extracting Map types. * * It's like `Extract>` but better with edge cases. */ type ExtractMap = T extends any ? [StrictExtract>] extends [ ReadonlyMap ] ? Extract> : [StrictExtract>] extends [Map] ? Extract> : Map extends T ? Map : never : never; /** * Check if two maps are equal. Items are checked for deep equality * using the `isEqual` function. * * @see https://radashi.js.org/reference/typed/isMapEqual * @version 12.7.0 */ declare function isMapEqual(x: Map, y: Map): boolean; /** * Return true if the given value is null or undefined. * * @see https://radashi.js.org/reference/typed/isNullish * @example * ```ts * isNullish(null) // => true * isNullish(undefined) // => true * isNullish('') // => false * isNullish(0) // => false * ``` * @version 12.3.0 */ declare function isNullish(value: unknown): value is null | undefined; /** * Return true if the given value is a number. * * @see https://radashi.js.org/reference/typed/isNumber * @example * ```ts * isNumber(0) // => true * isNumber('0') // => false * isNumber(NaN) // => true * ``` * @version 12.1.0 */ declare function isNumber(value: unknown): value is number; /** * Returns true if `value` is a plain object, a class instance * (excluding built-in classes like Date/RegExp), or an * `Object.create(null)` result. Objects from [other realms][1] are * also supported. * * Use this as a TypeScript type guard only when the input is known to * be either an object accepted by `isObject` or a non-object value. The * `object` type in TypeScript also includes arrays, functions, dates, * maps, sets, and other object-like values that `isObject` may reject * at runtime. * * [1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof#instanceof_and_multiple_realms * * @see https://radashi.js.org/reference/typed/isObject * @example * ```ts * isObject({}) // true * isObject(new Object()) // true * isObject(Object.create(null)) // true * isObject(new class {}) // true * * isObject([]) // false * isObject(/.+/g) // false * isObject(new Date()) // false * isObject(new Map()) // false * isObject(new Set()) // false * ``` * @version 12.1.0 */ declare function isObject(value: unknown): value is object; /** * Return true if the given value is a plain object. * * @see https://radashi.js.org/reference/typed/isPlainObject * @example * ```ts * isPlainObject({}) // => true * isPlainObject(new Map()) // => false * ``` * @version 12.2.0 */ declare function isPlainObject(value: any): value is object; /** * Checks if the given value is primitive. * * Primitive types include: * - number * - string * - boolean * - symbol * - bigint * - undefined * - null * * @see https://radashi.js.org/reference/typed/isPrimitive * @example * ```ts * isPrimitive(0) // => true * isPrimitive(null) // => true * isPrimitive(undefined) // => true * isPrimitive('0') // => false * ``` * @version 12.1.0 */ declare function isPrimitive(value: any): boolean; /** * Returns true if the value is a Promise or has a `then` method. * * @see https://radashi.js.org/reference/typed/isPromise * @example * ```ts * isPromise(Promise.resolve(1)) // => true * isPromise({ then() {} }) // => true * isPromise(1) // => false * ``` * @version 12.1.0 */ declare function isPromise(value: any): value is PromiseLike; /** * Checks if the given value is a RegExp. * * Instances from [other realms][1] are also supported. * * [1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof#instanceof_and_multiple_realms * * @see https://radashi.js.org/reference/typed/isRegExp * @example * ```ts * isRegExp(/abc/) // => true * isRegExp('abc') // => false * ``` * @version 12.2.0 */ declare function isRegExp(value: unknown): value is RegExp; /** * Returns true if the value is a `Result` tuple. * * @see https://radashi.js.org/reference/typed/isResult * @example * ```ts * isResult([undefined, 42]) => true * isResult([new Error(), undefined]) => true * * // Tuple must be of length 2. * isResult([new Error()]) => false * isResult([undefined, true, undefined]) => false * * // Non-tuple values are false. * isResult([]) => false * isResult({}) => false * isResult(null) => false * * // Result tuples cannot have both a value and an error. * isResult([new Error(), true]) => false * ``` * @version 12.2.0 */ declare function isResult(value: unknown): value is Result; /** * Returns true if the value is an `Err` result. * * @see https://radashi.js.org/reference/typed/isResultErr * @example * ```ts * isResultErr([new Error(), undefined]) // true * isResultErr([undefined, "hello"]) // false * ``` * @version 12.2.0 */ declare function isResultErr(value: unknown): value is Err; /** * Returns true if the value is an `Ok` result. * * @see https://radashi.js.org/reference/typed/isResultOk * @example * ```ts * isResultOk([undefined, "hello"]) // true * isResultOk([new Error(), undefined]) // false * ``` * @version 12.2.0 */ declare function isResultOk(value: unknown): value is Ok; /** * Checks if the given value is a Set. * * Instances from [other realms][1] are also supported. * * [1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof#instanceof_and_multiple_realms * * @see https://radashi.js.org/reference/typed/isSet * @example * ```ts * isSet(new Set([1, 2, 3])) // => true * isSet(new Map([1, 2, 3])) // => false * ``` * @version 12.2.0 */ declare function isSet(value: Input): value is ExtractSet; /** * An absurdly complicated but accurate type for extracting Set types. * * It's like `Extract>` but better with edge cases. */ type ExtractSet = T extends any ? [StrictExtract>] extends [ReadonlySet] ? Extract> : [StrictExtract>] extends [Set] ? Extract> : Set extends T ? Set : never : never; /** * Check if two sets are equal. * * Note: This does NOT check for deep equality of the items. * * @see https://radashi.js.org/reference/typed/isSetEqual * @version 12.7.0 */ declare function isSetEqual(x: Set, y: Set): boolean; /** * Checks if the given value is a string. * * @see https://radashi.js.org/reference/typed/isString * @example * ```ts * isString('abc') // => true * isString(123) // => false * ``` * @version 12.1.0 */ declare function isString(value: unknown): value is string; /** * Checks if the given value is a symbol. * * @see https://radashi.js.org/reference/typed/isSymbol * @example * ```ts * isSymbol(Symbol('abc')) // => true * isSymbol('abc') // => false * ``` * @version 12.1.0 */ declare function isSymbol(value: unknown): value is symbol; /** * Compare the given tag to the result of `Object.prototype.toString`. * * ⚠️ You probably won't use this except when implementing another type guard. * * @internal * @example * ```ts * isTagged('foo', '[object String]') // true * ``` * @version 12.2.0 */ declare function isTagged(value: unknown, tag: string): boolean; /** * Checks if the given value is undefined. * * @see https://radashi.js.org/reference/typed/isUndefined * @example * ```ts * isUndefined(undefined) // => true * isUndefined(null) // => false * ``` * @version 12.3.0 */ declare function isUndefined(value: unknown): value is undefined; /** * Checks if the given value is a WeakMap. * * Instances from [other realms][1] are also supported. * * [1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof#instanceof_and_multiple_realms * * @see https://radashi.js.org/reference/typed/isWeakMap * @example * ```ts * isWeakMap(new WeakMap()) // => true * isWeakMap(new Map()) // => false * ``` * @version 12.2.0 */ declare function isWeakMap(value: unknown): value is WeakMap; /** * Checks if the given value is a WeakSet. * * Instances from [other realms][1] are also supported. * * [1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof#instanceof_and_multiple_realms * * @see https://radashi.js.org/reference/typed/isWeakSet * @example * * ```ts * isWeakSet(new WeakSet()) // => true * isWeakSet(new Set()) // => false * ``` * @version 12.2.0 */ declare function isWeakSet(value: unknown): value is WeakSet; export { AggregateErrorOrPolyfill as AggregateError, Any, type Assign, type Awaitable, type BoxedPrimitive, type BuiltInType, type CastArray, type CastArrayIfExists, type Class, type CloningStrategy, type Comparable, type ComparableProperty, type Comparator, type ComparatorMapping, type CompatibleProperty, type Concat, type Crush, type CustomClass, type CustomClassRegistry, type DebounceFunction, type DebounceOptions, type Debounced, DefaultCloningStrategy, DurationParser, type DurationShortUnit, type DurationString, type DurationUnit, type Err, type ExtractArray, type ExtractClass, type ExtractMap, type ExtractNotAny, type ExtractSet, type Falsy, FastCloningStrategy, type FilteredKeys, type Flip, type GuardReturnType, type Intersect, type IsExactType, type KeyFilter, type KeyFilterFunction, type LowercaseKeys, type MappedInput, type MappedOutput, type Mapping, type MappingFunction, type MemoCache, type MemoOptions, type Memoized, type MergeOptions, type Ok, type OnceFunction, type OptionalKeys, type OptionalMapping, type ParallelOptions, type Primitive, type PromiseDebounceFunction, type PromiseDebounced, type PromiseWithResolvers, QuantityParser, type QuantityString, type RequiredKeys, type Result, type ResultPromise, type RetryOptions, Semaphore, type SemaphoreAcquireOptions, SemaphorePermit, type Series, type Simplify, type SortArray, type StrictExtract, type SwitchAny, type SwitchNever, type ThrottledFunction, TimeoutError, type ToEmpty, type ToEmptyAble, type TraverseContext, type TraverseOptions, type TraverseVisitor, type TryitResult, type TypedArray, type UppercaseKeys, absoluteJitter, all, alphabetical, always, assert, assign, boil, callable, camel, capitalize, cartesianProduct, castArray, castArrayIfExists, castComparator, castMapping, chain, clamp, clone, cloneDeep, cluster, compose, concat, construct, counting, crush, dash, debounce, deburr, dedent, defer, diff, draw, escapeHTML, filterKey, first, flat, flip, fork, get, getErrorMessage, getOrInsert, getOrInsertComputed, group, guard, identity, inRange, intersects, invert, isArray, isArrayEqual, isAsyncIterable, isBigInt, isBoolean, isClass, isDangerousKey, isDate, isEmpty, isEqual, isError, isFloat, isFunction, isInt, isIntString, isIterable, isMap, isMapEqual, isNullish, isNumber, isObject, isPlainObject, isPrimitive, isPromise, isRegExp, isResult, isResultErr, isResultOk, isSet, isSetEqual, isString, isSymbol, isTagged, isUndefined, isWeakMap, isWeakSet, iterate, keys, last, lerp, list, listify, lowerize, map, mapEntries, mapKeys, mapValues, mapify, max, memo, memoLastCall, merge, mergeOptions, min, noop, objectify, omit, once, parallel, parseDuration, parseQuantity, partial, partob, pascal, pick, pluck, promiseChain, promiseDebounce, promiseMemo, proportionalJitter, proxied, queueByKey, random, range, reduce, remove, replace, replaceOrAppend, retry, round, select, selectFirst, series, set, shake, shift, shuffle, sift, similarity, sleep, snake, sort, sum, template, throttle, timeout, title, toFloat, toInt, toResult, toggle, traverse, trim, tryit as try, tryit, uid, unique, unzip, upperize, withResolvers, zip, zipToObject };