Skip to content

prefer-string-slice: Improve autofix#2950

Open
Promise2679 wants to merge 2 commits intosindresorhus:mainfrom
Promise2679:main
Open

prefer-string-slice: Improve autofix#2950
Promise2679 wants to merge 2 commits intosindresorhus:mainfrom
Promise2679:main

Conversation

@Promise2679
Copy link
Copy Markdown

closes #2505

I noticed this issue and attempted an implementation.

The rule now produces str.slice(0, -x) instead of str.slice(0, Math.max(0, str.length - x)) when x is a positive numeric literal.

Please let me know if there’s anything I should adjust.

@sindresorhus
Copy link
Copy Markdown
Owner

This still looks unsafe for non-interger numeric literals. The new shortcut accepts foo.length - 1.5 and fixes it to foo.slice(0, -1.5), but that changes behavior.

For example, with const value = 'abcdef', both value.substr(0, value.length - 1.5) and value.substring(0, value.length - 1.5) return abcd, while value.slice(0, -1.5) returns abcde. 0.5 is even worse because slice(0, -0.5) becomes an empty string.

This should only apply when the subtracted literal is a positive integer, not just any positive number.

@Promise2679
Copy link
Copy Markdown
Author

Thanks for the review! I've fixed it by adding an isDecimalInteger check and included the corresponding test cases.

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.

Improve prefer-string-slice autofix

2 participants