unicorn/prefer-array-some
Require .some() to test whether an array has a matching element
has suggestions
.some() answers "is there a match?" with true or false, and stops at the first one. The other ways to ask are longer, and some are wrong or slow:
if (items.find(fn))is false when the element it finds is0or""..filter(fn).length > 0tests every element and builds an array only to count it.
--fix-suggestions rewrites the .find(), .findLast() and .filter() forms to .some().
Configure#
Off by default. To turn it on:
bunfig.toml
[lint.rules]
"unicorn/prefer-array-some" = "error" # or "warn"Examples#
example.js4 problems
if (users.findPrefer .some(…) over .find(…) or .findLast(…).(user => user.isAdmin)) {
showAdminPanel();
}
const hasAdmin = users.findPrefer .some(…) over .find(…) or .findLast(…).(user => user.isAdmin) !== undefined;
const hasGuest = users.findIndexPrefer .some(…) over .findIndex(…) or .findLastIndex(…).(user => user.isGuest) !== -1;
const hasActive = users.filterPrefer .some(…) over non-zero length check from .filter(…).(user => user.isActive).length > 0;example.jsNo problems
if (users.some(user => user.isAdmin)) {
showAdminPanel();
}
const hasAdmin = users.some(user => user.isAdmin);
const hasGuest = users.some(user => user.isGuest);
const hasActive = users.some(user => user.isActive);Code that uses the element, the index or the count isn't reported:
example.jsNo problems
const admin = users.find(user => user.isAdmin);
const position = users.findIndex(user => user.isGuest);
const enough = users.filter(user => user.isActive).length > 2;