rearg
function
Creates a function that invokes func with arguments arranged according to the specified indexes.
Installation
Import
import { rearg } from '@tulx/utils';Source Code
Implementation
/**
* Creates a function that invokes func with arguments arranged according to the specified indexes.
*
* @param func - The function to rearrange arguments for.
* @param indexes - The arranged argument indexes.
* @returns Returns the new function.
*
* @example
* ```ts
* const rearged = rearg((a: string, b: string, c: string) => [a, b, c], [2, 0, 1]);
* rearged('b', 'c', 'a'); // ['a', 'b', 'c']
* ```
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function rearg<T extends (...args: any[]) => any>(
func: T,
indexes: readonly number[]
): (...args: unknown[]) => ReturnType<T> {
return function (this: unknown, ...args: unknown[]): ReturnType<T> {
const rearrangedArgs = indexes.map((index) => args[index]);
return func.apply(this, rearrangedArgs) as ReturnType<T>;
};
}
Example
import { rearg } from '@tulx/utils';
const rearged = rearg((a: string, b: string, c: string) => [a, b, c], [2, 0, 1]);
rearged('b', 'c', 'a'); // ['a', 'b', 'c']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.