Skip to content

Latest commit

 

History

History
127 lines (92 loc) · 2.6 KB

prefer-at.md

File metadata and controls

127 lines (92 loc) · 2.6 KB

Prefer .at() method for index access and String#charAt()

💼 This rule is enabled in the ✅ recommended config.

🔧💡 This rule is automatically fixable by the --fix CLI option and manually fixable by editor suggestions.

Prefer Array#at(), String#at(), and {TypedArray,NodeList,CSSRuleList,…}#at() for index access and String#charAt().

Fail

const foo = array[array.length - 1];
const foo = array[array.length - 5];
const foo = array.slice(-1)[0];
const foo = array.slice(-1).pop();
const foo = array.slice(-5).shift();
const foo = string.charAt(string.length - 5);
const foo = lodash.last(array);

Pass

const foo = array.at(-1);
const foo = array.at(-5);
const foo = array[100];
// This rule is not checking this case, but `unicorn/prefer-negative-index` rule will fix it.
const foo = array.at(array.length - 1);
array[array.length - 1] = foo;

Options

Type: object

checkAllIndexAccess

Type: boolean
Default: false

This rule only check negative indexes by default, but you can also check positive indexes by setting checkAllIndexAccess to true.

Example:

{
	'unicorn/prefer-at': [
		'error',
		{
			checkAllIndexAccess: true
		}
	]
}
// eslint unicorn/prefer-at: ["error", {"checkAllIndexAccess": true}]
const foo = bar[10]; // Fails, will fix to `bar.at(10)`
const foo = bar[unknownProperty]; // Passes
const foo = string.charAt(unknownIndex); // Fails

getLastElementFunctions

Type: string[]

You can also check custom functions that get last element of objects.

_.last(), lodash.last(), and underscore.last() are always checked.

Example:

{
	'unicorn/prefer-at': [
		'error',
		{
			getLastElementFunctions: [
				'getLast',
				'utils.lastElement'
			]
		}
	]
}
// eslint unicorn/prefer-at: ["error", {"getLastElementFunctions": ["utils.lastElement"]}]
const foo = utils.lastElement(bar); // Fails

Related rules