Back to Functions

ary

function

Creates a function that invokes func, with up to n arguments, ignoring any additional arguments.

Installation

Import
import { ary } from '@tulx/utils';

Source Code

Implementation
/**
 * Creates a function that invokes func, with up to n arguments, ignoring any additional arguments.
 *
 * @param func - The function to cap arguments for.
 * @param n - The arity cap.
 * @returns Returns the new capped function.
 *
 * @example
 * ```ts
 * map(['6', '8', '10'], ary(parseInt, 1)); // [6, 8, 10]
 * ```
 */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function ary<T extends (...args: any[]) => any>(
  func: T,
  n: number
): (...args: Parameters<T>) => ReturnType<T> {
  return function (this: unknown, ...args: Parameters<T>): ReturnType<T> {
    return func.apply(this, args.slice(0, n)) as ReturnType<T>;
  };
}

Example

import { ary } from '@tulx/utils';

map(['6', '8', '10'], ary(parseInt, 1)); // [6, 8, 10]

Related Functions