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

es6: prefer String.startsWith() and String.includes() #565

Open
6 tasks
NovemLinguae opened this issue Apr 18, 2024 · 5 comments
Open
6 tasks

es6: prefer String.startsWith() and String.includes() #565

NovemLinguae opened this issue Apr 18, 2024 · 5 comments

Comments

@NovemLinguae
Copy link

NovemLinguae commented Apr 18, 2024

String.startsWith() and String.includes() were introduced in ES6 and are great. Very readable.

  • Warn or error on String.indexOf(a) !== -1, suggest String.includes() instead
    • Autofix
  • Warn or error on String.indexOf(a) === 0, suggest String.startsWith() instead
    • Autofix

Source code from another eslint plugin with these rules here and here (MIT license)


edit: Array.indexOf() !== -1 is also a very common pattern. Might also want to tackle it at the same time.

  • Warn or error on Array.indexOf(a) !== -1, suggest Array.includes() instead
    • Autofix

Careful of this pattern when autofixing: (badIndex = params.tags.indexOf('Bad GIF')) !== -1. That should not be autofixed due to the variable depending on getting the indexOf's value.

@edg2s
Copy link
Member

edg2s commented Apr 18, 2024

We can use the already present unicorn plugin for startsWith:

@edg2s
Copy link
Member

edg2s commented Apr 18, 2024

Alternatively the rules could be applied to ES2016 rules only, where Array.indexOf can also be replaced by Array.includes, and so the type wouldn't matter

@NovemLinguae
Copy link
Author

NovemLinguae commented Nov 13, 2024

543 hits in CodeSearch for !== -1, and 200 for === 0. Lots of good potential autofixing here.

edit: Actually, some of those may be Array.indexOf().

@NovemLinguae
Copy link
Author

NovemLinguae commented Dec 19, 2024

Looks like unicorn/prefer-starts-ends-with only catches RegEx, not indexOf.

Once #599 is merged, though, we can turn on unicorn/prefer-includes, and then let LibUp run autofixes for it. It looks like that one will convert all Array.indexOf to Array.includes for us.

Example autofixes in Twinkle.

@NovemLinguae
Copy link
Author

Note that unicorn/prefer-includes autofixes are buggy sometimes, so be careful with it. Example: https://en.wikipedia.org/wiki/MediaWiki_talk:Gadget-popups.js#str.includes_is_not_a_function

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

No branches or pull requests

2 participants