sindresorhus / eslint-plugin-unicorn

More than 100 powerful ESLint rules
MIT License
4.03k stars 359 forks source link

Rule proposal: Prefer `matchAll` #574

Open brettz9 opened 4 years ago

brettz9 commented 4 years ago

Not offering a PR here, but just thought such a rule could possibly fit your project...

Namely, preferring String.prototype.matchAll to while loop exec assignments.

As per https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/matchAll#Examples , one can replace this:

let match;
while ((match = regexp.exec(str)) !== null) {
}

..with the likes of:

for (const match of str.matchAll(regexp)) {
}

I find it quite a bit more elegant and semantic, and it allows avoiding defining a variable in the parent block.

If not, no worries, just thought I'd see if it might pique the interest of others.

sindresorhus commented 4 years ago

I like it, but the rule needs to be off by default for now as .matchAll requires Node.js 12.

sindresorhus commented 4 years ago

This is now accepted. PR welcome :)

aggmoulik commented 3 years ago

Can anyone please provide some test cases for the same ?

brettz9 commented 6 months ago

Sorry for the delayed reply. Re: test cases, I can mostly just think of the failing case in the OP (and its reverse while (null !== (match = regexp.exec(str))) {), as well as this being left as is (passing):

let match;
while ((match = regexp.exec(str)) !== null) {
  // ...
}
return match; // If `match` is used outside of the block, do not report/fix