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

Fix(prefer-at): remove unsafe autofix for .slice with 1 argument #2476

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

k-yle
Copy link

@k-yle k-yle commented Oct 11, 2024

It's not safe to change array.slice(-n)[0] to array.at(-n). This code is not equivalent for arrays with only 1 item. It's only equivalent for .slice(-1)

Proof:

testCases = [ 'a', 'ab', 'abc', 'abcd' ];
testCases.map(array => ({
    original: array.slice(-2)[0],
    autofixed: array.at(-2),
}));

// output:
[ 
  {original: 'a', autofixed: undefined}, // 🔴 this is different
  {original: 'a', autofixed: 'a'},
  {original: 'b', autofixed: 'b'},
  {original: 'c', autofixed: 'c'},
]

@github-actions github-actions bot changed the title fix(prefer-at): remove unsafe autofix for .slice with 1 argument Fix(prefer-at): remove unsafe autofix for .slice with 1 argument Oct 11, 2024
firstElementGetMethod === 'zero-index'
|| firstElementGetMethod === 'shift'
|| (startIndex === -1 && firstElementGetMethod === 'pop')
)
Copy link
Collaborator

Choose a reason for hiding this comment

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

This is incorrect, the value of startIndexNode doesn't matter. It only result differently when the index is out of the boundary of string. And sting don't have .shift/.pop, so it doesn't matter.

Copy link
Author

Choose a reason for hiding this comment

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

@fisker we're checking startIndexNode because .slice(-1)[0] can still be safely converted to .at(-1), but only for -1, not any other number. For any other number the behaviour is different if the index is out of bounds

Copy link
Collaborator

Choose a reason for hiding this comment

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

You are right.

But i think we should still report array.slice(-9)[0], just remove the autofix.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants