Helper function to get function arity by analyzing parameter lists for assignment patterns and rest parameters
npx @tessl/cli install tessl/npm-babel--helper-get-function-arity@7.16.0Helper function to get function arity by analyzing parameter lists for assignment patterns and rest parameters. This utility determines the effective arity (number of required parameters) of JavaScript functions, which is essential for Babel transformations that need to understand function signatures.
npm install @babel/helper-get-function-arityimport getFunctionArity from "@babel/helper-get-function-arity";For CommonJS:
const getFunctionArity = require("@babel/helper-get-function-arity");import getFunctionArity from "@babel/helper-get-function-arity";
import * as t from "@babel/types";
// Example with a function that has no optional parameters
const regularFunction = t.functionExpression(
null,
[t.identifier("a"), t.identifier("b"), t.identifier("c")],
t.blockStatement([])
);
const arity1 = getFunctionArity(regularFunction); // Returns: 3
// Example with a function that has default parameters
const functionWithDefaults = t.functionExpression(
null,
[
t.identifier("a"),
t.assignmentPattern(t.identifier("b"), t.numericLiteral(10)),
t.identifier("c")
],
t.blockStatement([])
);
const arity2 = getFunctionArity(functionWithDefaults); // Returns: 1
// Example with a function that has rest parameters
const functionWithRest = t.functionExpression(
null,
[
t.identifier("a"),
t.identifier("b"),
t.restElement(t.identifier("rest"))
],
t.blockStatement([])
);
const arity3 = getFunctionArity(functionWithRest); // Returns: 2Determines the effective arity of JavaScript functions by finding the first optional or rest parameter.
/**
* Get the effective arity of a function by analyzing its parameter list
* @param node - A Babel AST node representing any function type
* @returns The index of the first optional parameter, or total parameter count if all are required
*/
function getFunctionArity(node: t.Function): number;The function analyzes the params array of the function node and:
isAssignmentPattern()isRestElement()type Function =
| FunctionDeclaration
| FunctionExpression
| ObjectMethod
| ArrowFunctionExpression
| ClassMethod
| ClassPrivateMethod;All these function types have a params property of type Array<Identifier | Pattern | RestElement>.
type Identifier = {
type: "Identifier";
name: string;
};
type AssignmentPattern = {
type: "AssignmentPattern";
left: Pattern;
right: Expression;
};
type RestElement = {
type: "RestElement";
argument: Pattern;
};This package depends on @babel/types for:
isAssignmentPattern() utility function for detecting default parametersisRestElement() utility function for detecting rest parametersThis helper is commonly used in Babel plugins and transformations where understanding function signatures is crucial: