Helper function to get function arity by analyzing parameter lists for assignment patterns and rest parameters
95
Build a utility that analyzes JavaScript function parameter patterns and provides detailed insights about their structure, focusing on determining required versus optional parameters.
Your task is to implement a function analyzer that takes JavaScript function code as a string and returns analysis about its parameter structure.
The analyzer should accept a string containing a JavaScript function definition. Examples include:
function example(a, b, { c = 5 }) {}const arrow = (x, { y, z = 10 } = {}, ...rest) => {}Return an object containing:
requiredCount - The number of parameters that must be provided when calling the functiontotalCount - The total number of parameters defined (excluding rest parameters)hasRest - Boolean indicating if a rest parameter is presentpatterns - An array describing each parameter type: "identifier", "destructuring", or "rest"@babel/parserGiven function add(a, b) {}, returns {requiredCount: 2, totalCount: 2, hasRest: false, patterns: ["identifier", "identifier"]} @test
Given function greet(name, greeting = "Hello") {}, returns {requiredCount: 1, totalCount: 2, hasRest: false, patterns: ["identifier", "identifier"]} @test
Given function process(data, { format = "json" }) {}, returns {requiredCount: 1, totalCount: 2, hasRest: false, patterns: ["identifier", "destructuring"]} @test
Given function collect(first, ...rest) {}, returns {requiredCount: 1, totalCount: 1, hasRest: true, patterns: ["identifier", "rest"]} @test
@generates
/**
* Analyzes a JavaScript function's parameter structure
*
* @param {string} functionCode - JavaScript function code to analyze
* @returns {Object} Analysis result with requiredCount, totalCount, hasRest, and patterns
*/
function analyzeParameters(functionCode) {
// Implementation here
}
module.exports = { analyzeParameters };Provides JavaScript parsing capabilities to convert function code into an AST.
Provides utility to determine the effective arity of a function by analyzing its parameter list.
Provides utilities for checking AST node types and working with Babel's AST structure.
Install with Tessl CLI
npx tessl i tessl/npm-babel--helper-get-function-aritydocs
evals
scenario-1
scenario-2
scenario-3
scenario-4
scenario-5
scenario-6
scenario-7
scenario-8
scenario-9
scenario-10