CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-babel--helper-get-function-arity

Helper function to get function arity by analyzing parameter lists for assignment patterns and rest parameters

95

1.06x
Overview
Eval results
Files

task.mdevals/scenario-1/

Function Arity Validator Plugin

Create a Babel plugin that validates function calls to ensure they provide the minimum required number of arguments based on the function's arity.

Overview

When calling functions with insufficient arguments, JavaScript allows the call but may lead to unexpected behavior. Your task is to build a Babel plugin that analyzes function calls during compilation and adds runtime validation to ensure callers provide at least the minimum required arguments.

Requirements

Plugin Behavior

Your plugin should:

  1. Analyze all function declarations, function expressions, and arrow functions in the code
  2. For each function, determine how many required parameters it has (parameters before the first optional or rest parameter)
  3. Generate a wrapper function that validates the argument count at runtime
  4. Replace the original function with the wrapper that throws an error if insufficient arguments are provided

Validation Logic

  • The wrapper should check if the number of arguments provided is less than the required arity
  • If insufficient arguments are detected, throw an error with the message: "Expected at least X arguments, but got Y"
  • If sufficient arguments are provided, call the original function with all provided arguments

Implementation

@generates

API

/**
 * Babel plugin that validates function call arity at runtime
 *
 * @returns {Object} Babel plugin object with visitor methods
 */
export default function arityValidatorPlugin() {
  // IMPLEMENTATION HERE
}

Test Cases

  • A function with 2 required parameters (e.g., function add(a, b) {}) gets wrapped with validation that ensures at least 2 arguments are provided @test
  • A function with 1 required parameter and 1 optional parameter (e.g., function greet(name, title = "Mr.") {}) gets wrapped to require at least 1 argument @test
  • A function with all optional parameters (e.g., function config(a = 1, b = 2) {}) gets wrapped to require 0 arguments @test
  • The wrapped function throws an error with the correct message when called with insufficient arguments @test

Dependencies { .dependencies }

@babel/helper-get-function-arity { .dependency }

Helper function to get function arity by analyzing parameter lists for assignment patterns and rest parameters.

@babel/types { .dependency }

Provides utilities for AST node type checking and creation.

Install with Tessl CLI

npx tessl i tessl/npm-babel--helper-get-function-arity

tile.json