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

prefer-at should also mark substrings of length 1 #2203

Open
ST-DDT opened this issue Oct 22, 2023 · 4 comments
Open

prefer-at should also mark substrings of length 1 #2203

ST-DDT opened this issue Oct 22, 2023 · 4 comments

Comments

@ST-DDT
Copy link
Contributor

ST-DDT commented Oct 22, 2023

Description

The prefer-at rule should also check for substrings of length 1.

Fail

string.substring(0, 1)
string.substring(value, value + 1)
string.substring(value, 1 + value)
string.substring(value - 1, value)

Pass

string[0]
string[value]
string[value - 1]

or

string.at(0)
string.at(value)
string.at(value - 1)

And maybe:

string.charAt(0)
string.charAt(value)
string.charAt(value - 1)

Additional Info

No response

@fisker
Copy link
Collaborator

fisker commented Oct 26, 2023

It's a good idea.

But we have a problem to add this rule.
We already have prefer-string-slice rule enforce users move to String#slice().

And we can't check foo.slice(0, 1), since foo can be an array or something else with .slice() unless we have type information.

@sindresorhus
Copy link
Owner

While not ideal, the common solution for this is to introduce an option to prefer-string-slice to ignore substrings of length 1.

@sindresorhus
Copy link
Owner

Accepted.

@sindresorhus sindresorhus changed the title Rule proposal: prefer-at should also mark substrings of length 1 prefer-at should also mark substrings of length 1 Oct 30, 2023
@ST-DDT
Copy link
Contributor Author

ST-DDT commented Oct 30, 2023

While not ideal, the common solution for this is to introduce an option to prefer-string-slice to ignore substrings of length 1.

IMO there is no need for a new option, as slice is effectively a substring and thus should also use .charAt/at when possible.

EDIT: Oh I see.
Is there a way to give the prefer-at rule a higher priority than slice? So that it's fixers run first?

Because the option is prone to being configured wrong.
E.g. if it is enabled by default, but prefer-at is not, then it misses changes. If it is not enabled by default, then it is most likely forgotten during initial apply and thus all substrings of length 1 already use slice.

Edit2: Maybe this will end up with requiring type information anyway. 🤷

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

No branches or pull requests

3 participants