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

Rule proposal: Prefer .includes() #284

Closed
sindresorhus opened this issue Feb 14, 2019 · 2 comments · Fixed by #294
Closed

Rule proposal: Prefer .includes() #284

sindresorhus opened this issue Feb 14, 2019 · 2 comments · Fixed by #294
Labels
enhancement: new plugin rule New rule request for eslint-plugin package: eslint-plugin Issues related to @typescript-eslint/eslint-plugin

Comments

@sindresorhus
Copy link

This rule should prefer .includes() over .indexOf() when checking for existence. This would apply to the following types: String#includes, Array#includes, TypedArray#includes, Buffer#includes.

.includes() cases:

  • 'foobar'.indexOf('foo') !== -1
  • 'foobar'.indexOf('foo') != -1
  • 'foobar'.indexOf('foo') > -1
  • 'foobar'.indexOf('foo') >= 0

These would negate .includes():

  • 'foobar'.indexOf('foo') == -1
  • 'foobar'.indexOf('foo') === -1
  • 'foobar'.indexOf('foo') < 0

It would also be useful to catch cases where String#includes() would be better than a regex: /\r\n/.test(foo); => foo.includes('\r\n');


This was originally proposed for inclusion in ESLint, but declined for lack of type knowledge in JS.

@sindresorhus sindresorhus added package: eslint-plugin Issues related to @typescript-eslint/eslint-plugin triage Waiting for maintainers to take a look labels Feb 14, 2019
@j-f1 j-f1 added enhancement: new plugin rule New rule request for eslint-plugin and removed triage Waiting for maintainers to take a look labels Feb 14, 2019
@mysticatea
Copy link
Member

I will work on this.

I think that I'd like to separate this to two rules:

  • prefer-array-includes ... for Array, ReadonlyArray, typed arrays, and child classes of those (Buffer extends Uint8Array). Array#includes has been added in ES2016.
  • prefer-string-includes ... for strings. This address regular expressions as suggested. String#includes has been added in ES2015.

Thoughts?

@mysticatea
Copy link
Member

After re-tought, I will go with one rule:

  • prefer-includes ... for all types which have both indexOf method and includes method, if the parameter types of those methods are same completely, the rule suggests to use includes method.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
enhancement: new plugin rule New rule request for eslint-plugin package: eslint-plugin Issues related to @typescript-eslint/eslint-plugin
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants