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

Add option for prefer-string-slice autofixes to not use Math.max #2505

Open
NovemLinguae opened this issue Dec 6, 2024 · 3 comments
Open

Comments

@NovemLinguae
Copy link

unicorn/prefer-string-slice is good when all the parameters are constants, or when there is only one parameter. But when there are two parameters and they're variables, the autofixes will do things like this:

editsummary = editsummary.substr(0, editsummary.length - 2); // remove trailing comma
->
editsummary = editsummary.slice(0, Math.max(0, editsummary.length - 2)); // remove trailing comma

I find the Math.max pretty hard to read. I'd prefer that it not autofix that particular sub-pattern. Any interest in adding an option to this rule so that it can be configured to skip that particular sub-pattern when autofixing?

@github-actions github-actions bot changed the title add option for prefer-string-slice autofixes to not use Math.max Add option for prefer-string-slice autofixes to not use Math.max Dec 6, 2024
@edg2s
Copy link

edg2s commented Dec 6, 2024

n.b. you should only autofix if the number being substracted is a literal you know to be non-zero.

string = string.slice( 0, string.length - y )

is usally equal to

string = string.slice( 0, -y )

but if y is 0 string.slice( 0, -0 ) gives you the empty string instead of the whole of string

@fregante
Copy link
Collaborator

Add option for prefer-string-slice autofixes to not use Math.max

Autofixes should be safe, an option shouldn't change that.

I think this suggestion would be to improve the autofix of this specific scenario from:

- STR.substr(0, STR.length - NUM)
+ STR.slice(0, Math.max(0, STR.length - NUM))

To:

- STR.substr(0, STR.length - NUM)
+ STR.slice(0, -NUM)

As long as the behavior is always the same.

@NovemLinguae
Copy link
Author

Agreed that we shouldn't ever do unsafe autofixes. My original idea was to add an option to skip rather than incorrectly fix.

Changing to STR.slice(0, -NUM) would be fantastic, assuming it's completely equivalent. Much less verbose.

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