bind
function
Creates a function that invokes func with the this binding of thisArg and partials prepended to the arguments it receives.
Installation
Import
import { bind } from '@tulx/utils';Source Code
Implementation
/**
* Creates a function that invokes func with the this binding of thisArg and partials prepended to the arguments it receives.
*
* @param func - The function to bind.
* @param thisArg - The this binding of func.
* @param partials - The arguments to be partially applied.
* @returns Returns the new bound function.
*
* @example
* ```ts
* const greet = function(greeting: string, punctuation: string) {
* return greeting + ' ' + this.user + punctuation;
* };
* const object = { 'user': 'fred' };
* const bound = bind(greet, object, 'hi');
* bound('!'); // 'hi fred!'
* ```
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function bind<T extends (...args: any[]) => any>(
func: T,
thisArg: unknown,
...partials: readonly unknown[]
): (...args: unknown[]) => ReturnType<T> {
return function (this: unknown, ...args: unknown[]): ReturnType<T> {
return func.apply(thisArg, [...partials, ...args]) as ReturnType<T>;
};
}
Example
import { bind } from '@tulx/utils';
const greet = function(greeting: string, punctuation: string) {
return greeting + ' ' + this.user + punctuation;
};
const object = { 'user': 'fred' };
const bound = bind(greet, object, 'hi');
bound('!'); // 'hi fred!'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.
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.
curryRight
This method is like curry except that arguments are applied to func in the manner of partialRight instead of partial.