eslint-plugin-unicorn icon indicating copy to clipboard operation
eslint-plugin-unicorn copied to clipboard

Rule proposal: `call-arguments-length`

Open fisker opened this issue 4 years ago • 5 comments

A generic rule to enforce correct call arguments length.

For example CanvasRenderingContext2D.drawImage() can config as {'*.drawImage': [3, 5, 9]}, so it must be called with 3 or 5 or 9 arguments.

// Fail
context.drawImage(image, dx);
context.drawImage(image, dx, dy, dWidth, );

// Pass
context.drawImage(image, dx, dy);

This rule accepts a configurable list, for each method of function, value can be a number or a range, or allowed lengths.

{
	rules: {
		'unicorn/call-arguments-length':[
			'error',
			{
				'parseInt': 2,
				'*.drawImage': [3, 5, 9],
				'*.addEventListener': {min: 2}
			}
		]
	}
}

Ref: https://github.com/sindresorhus/eslint-plugin-unicorn/issues/974#issuecomment-768746222

fisker avatar Jun 15 '21 10:06 fisker

I think we should ship with a default preset for this rule that covers a lot of built-ins.

sindresorhus avatar Jul 01 '21 07:07 sindresorhus

This is now accepted.

sindresorhus avatar Jul 01 '21 07:07 sindresorhus

This rule should support new expression.

{
  rules: {
    'unicorn/call-arguments-length': ['error', {
      'parseInt': 2,
      '*.drawImage': [3, 5, 9],
      '*.addEventListener': {min: 2},
      'new Set': {max: 1}
    }]
  }
}

One edge case: spreading operator like new Set(...args) should be regarded as 1 argument?

zanminkian avatar Sep 17 '24 15:09 zanminkian

I think spreading parameters should be regarded as error if the function has specified the arguments length

// config
{
  rules: {
    'unicorn/call-arguments-length': ['error', {
      'new Set': {max: 1}
    }]
  }
}

// code
new Set(); // pass
new Set(foo); // pass
new Set(...foo); // fail

So that, the issue #2412 can be solved by this rule.

zanminkian avatar Sep 17 '24 17:09 zanminkian

Addition: we can remove or deprecate unicorn/error-message rule if the default config of this rule contains the restriction about new Error

// config
{
  rules: {
    'unicorn/call-arguments-length': ['error', {
      "new Error": {min:1},
      "new TypeError": {min:1},
      "new AggregateError": {min:2}
    }]
  }
}

new Error(); // fail
new TypeError('foo') // pass

zanminkian avatar Nov 30 '24 16:11 zanminkian