Skip to content

Commit

Permalink
Merge pull request #114 from ShridharGoel/useat-
Browse files Browse the repository at this point in the history
Handle functions and assignment in prefer-at condition
  • Loading branch information
roryabraham authored Aug 23, 2024
2 parents dbf4527 + b2de406 commit fc5dc90
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 0 deletions.
12 changes: 12 additions & 0 deletions eslint-plugin-expensify/prefer-at.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
const { AST_NODE_TYPES, ESLintUtils } = require('@typescript-eslint/utils');
const message = require('./CONST').MESSAGE.PREFER_AT;

const { isLeftHandSide } = require('./utils/is-left-hand-side');

module.exports = {
meta: {
fixable: 'code',
Expand Down Expand Up @@ -73,6 +75,16 @@ module.exports = {
return;
}

// Skip if the property is a method (like a?.map)
if (node.parent && node.parent.type === AST_NODE_TYPES.CallExpression && node.parent.callee === node) {
return;
}

// Skip if the node is part of an assignment expression
if (isLeftHandSide(node)) {
return;
}

const indexExpression = parseExpression(node.property);

if (indexExpression !== null && indexExpression !== 'length' && indexExpression !== 'at') {
Expand Down
6 changes: 6 additions & 0 deletions eslint-plugin-expensify/tests/prefer-at.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,12 @@ ruleTester.run('prefer-at', rule, {
{
code: 'const a = ["a", "b", "c"] as const; a[0]',
},
{
code: 'const example = [1, 2, 3, 4]; example.map(x => x * 2);',
},
{
code: 'const example = [1, 2, 3, 4]; const x = 1; example[x] = 5;',
},
],
invalid: [
{
Expand Down
27 changes: 27 additions & 0 deletions eslint-plugin-expensify/utils/is-left-hand-side.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
// https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/rules/utils/is-left-hand-side.js

const { AST_NODE_TYPES } = require('@typescript-eslint/utils');

function isLeftHandSide(node) {
const { parent } = node;

return (
(parent.type === AST_NODE_TYPES.AssignmentExpression || parent.type === AST_NODE_TYPES.AssignmentPattern)
&& parent.left === node
)
|| (parent.type === AST_NODE_TYPES.UpdateExpression && parent.argument === node)
|| (parent.type === AST_NODE_TYPES.ArrayPattern && parent.elements.includes(node))
|| (
parent.type === AST_NODE_TYPES.Property
&& parent.value === node
&& parent.parent.type === AST_NODE_TYPES.ObjectPattern
&& parent.parent.properties.includes(parent)
)
|| (
parent.type === AST_NODE_TYPES.UnaryExpression
&& parent.operator === 'delete'
&& parent.argument === node
);
}

module.exports = { isLeftHandSide };

0 comments on commit fc5dc90

Please sign in to comment.