| 1 | import { Many } from '../_internal/Many.js';
|
|---|
| 2 |
|
|---|
| 3 | /**
|
|---|
| 4 | * Creates a function that invokes `func` with its arguments transformed by corresponding transform functions.
|
|---|
| 5 | *
|
|---|
| 6 | * Transform functions can be:
|
|---|
| 7 | * - Functions that accept and return a value
|
|---|
| 8 | * - Property names (strings) to get a property value from each argument
|
|---|
| 9 | * - Objects to check if arguments match the object properties
|
|---|
| 10 | * - Arrays of [property, value] to check if argument properties match values
|
|---|
| 11 | *
|
|---|
| 12 | * If a transform is nullish, the identity function is used instead.
|
|---|
| 13 | * Only transforms arguments up to the number of transform functions provided.
|
|---|
| 14 | *
|
|---|
| 15 | * @param {(...args: any[]) => any} func - The function to wrap
|
|---|
| 16 | * @param {Array<Many<(...args: any[]) => any>>} transforms - The functions to transform arguments. Each transform can be:
|
|---|
| 17 | * - A function that accepts and returns a value
|
|---|
| 18 | * - A string to get a property value (e.g. 'name' gets the name property)
|
|---|
| 19 | * - An object to check if arguments match its properties
|
|---|
| 20 | * - An array of [property, value] to check property matches
|
|---|
| 21 | * @returns {(...args: any[]) => any} A new function that transforms arguments before passing them to func
|
|---|
| 22 | * @throws {TypeError} If func is not a function.
|
|---|
| 23 | * @example
|
|---|
| 24 | * ```ts
|
|---|
| 25 | * function doubled(n: number) {
|
|---|
| 26 | * return n * 2;
|
|---|
| 27 | * }
|
|---|
| 28 | *
|
|---|
| 29 | * function square(n: number) {
|
|---|
| 30 | * return n * n;
|
|---|
| 31 | * }
|
|---|
| 32 | *
|
|---|
| 33 | * const func = overArgs((x, y) => [x, y], [doubled, square]);
|
|---|
| 34 | *
|
|---|
| 35 | * func(5, 3);
|
|---|
| 36 | * // => [10, 9]
|
|---|
| 37 | *
|
|---|
| 38 | * // With property shorthand
|
|---|
| 39 | * const user = { name: 'John', age: 30 };
|
|---|
| 40 | * const getUserInfo = overArgs(
|
|---|
| 41 | * (name, age) => `${name} is ${age} years old`,
|
|---|
| 42 | * ['name', 'age']
|
|---|
| 43 | * );
|
|---|
| 44 | * getUserInfo(user, user);
|
|---|
| 45 | * // => "John is 30 years old"
|
|---|
| 46 | * ```
|
|---|
| 47 | */
|
|---|
| 48 | declare function overArgs(func: (...args: any[]) => any, ..._transforms: Array<Many<(...args: any[]) => any>>): (...args: any[]) => any;
|
|---|
| 49 |
|
|---|
| 50 | export { overArgs };
|
|---|