overArgs
function
Creates a function that invokes func with its arguments transformed.
Installation
Import
import { overArgs } from '@tulx/utils';Source Code
Implementation
/**
* Creates a function that invokes func with its arguments transformed.
*
* @param func - The function to wrap.
* @param transforms - The argument transforms.
* @returns Returns the new function.
*
* @example
* ```ts
* function doubled(n: number) {
* return n * 2;
* }
* function square(n: number) {
* return n * n;
* }
* const func = overArgs((x: number, y: number) => [x, y], [square, doubled]);
* func(9, 3); // [81, 6]
* ```
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function overArgs<T extends (...args: any[]) => any>(
func: T,
transforms: readonly ((arg: unknown) => unknown)[]
): (...args: unknown[]) => ReturnType<T> {
return function (this: unknown, ...args: unknown[]): ReturnType<T> {
const transformedArgs = args.map((arg, index) => {
const transform = transforms[index];
return transform ? transform(arg) : arg;
});
return func.apply(this, transformedArgs) as ReturnType<T>;
};
}
Example
import { overArgs } from '@tulx/utils';
function doubled(n: number) {
return n * 2;
}
function square(n: number) {
return n * n;
}
const func = overArgs((x: number, y: number) => [x, y], [square, doubled]);
func(9, 3); // [81, 6]Related Functions
after
The opposite of before; this method creates a function that invokes func once it's called n or more times.
ary
Creates a function that invokes func, with up to n arguments, ignoring any additional arguments.
before
Creates a function that invokes func, with the this binding and arguments of the created function, while it's called less than n times.
bind
Creates a function that invokes func with the this binding of thisArg and partials prepended to the arguments it receives.
bindKey
Creates a function that invokes the method at object[key] with partials prepended to the arguments it receives.
curry
Creates a function that accepts arguments of func and either invokes func returning its result, or returns a function that accepts the remaining arguments.