Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle functions and assignment in prefer-at condition #114

Merged
merged 6 commits into from
Aug 23, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions eslint-plugin-expensify/prefer-at.js
Original file line number Diff line number Diff line change
Expand Up @@ -67,12 +67,26 @@ module.exports = {
return indexExpression;
}

function isAssignmentExpression(node) {
return node.parent && node.parent.type === AST_NODE_TYPES.AssignmentExpression && node.parent.left === node;
}

function checkNode(node) {
if (node.type === AST_NODE_TYPES.MemberExpression && node.property) {
if (!isArrayType(node.object)) {
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 (like a[i] = 2)
if (isAssignmentExpression(node)) {
return;
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We want to return early if node is left-hand side right? If so, I think it'll be better to wrap them in method. I'm not sure if there's a similar method from @typescript-eslint/utils

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ShridharGoel I did some search and found a similar implementation from this project eslint-plugin-unicorn (under MIT license) and there's a isLeftHandSide method. Maybe we can learn some ideas from there to make our implementation more robust.


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