🔧💡 This rule is automatically fixable by the
--fix CLI option
and manually fixable by
editor suggestions.
This rule is only meant to enforce a specific style and make comparisons more clear.
This rule is fixable, unless it's unsafe to fix.
Enforce comparison with === 0 when checking for zero size.
const isEmpty = !foo.size();const isEmpty = foo.size() < 1;const isEmpty = 0 === foo.size();const isEmpty = 1 > foo.size();// Negative style is disallowed too
const isEmpty = !(foo.size() > 0);const isEmptySet = !foo.size();const isEmpty = foo.size() === 0;Enforce comparison with > 0 when checking for non-zero size.
const isNotEmpty = foo.size() !== 0;const isNotEmpty = foo.size() >= 1;const isNotEmpty = 0 !== foo.size();const isNotEmpty = 0 < foo.size();const isNotEmpty = 1 <= foo.size();// Negative style is disallowed too
const isNotEmpty = !(foo.size() === 0);if (foo.size() || bar.size()) {
}const unicorn = foo.size() ? 1 : 2;while (foo.size()) {}do {} while (foo.size());while (foo.size()) {}const isNotEmpty = foo.size() > 0;if (foo.size() > 0 || bar.size() > 0) {
}You can define your preferred way of checking non-zero size by providing a
non-zero option (greater-than by default):
{
"sentinel/explicit-size-check": [
"error",
{
"non-zero": "not-equal"
}
]
}The non-zero option can be configured with one of the following:
greater-than(default)- Enforces non-zero to be checked with:
foo.size() > 0
- Enforces non-zero to be checked with:
not-equal- Enforces non-zero to be checked with:
foo.size() !== 0
- Enforces non-zero to be checked with:
.size() check inside LogicalExpressions are not safe to fix.
Example:
const bothNotEmpty = (a, b) => a.size() && b.size();
if (bothNotEmpty(foo, bar)) {
}In this case, the bothNotEmpty function returns a number, but it will most
likely be used as a boolean. The rule will still report this as an error, but
without an auto-fix. You can apply a
suggestion
in your editor, which will fix it to:
const bothNotEmpty = (a, b) => a.size() > 0 && b.size() > 0;
if (bothNotEmpty(foo, bar)) {
}The rule is smart enough to know some LogicalExpressions are safe to fix, like
when it's inside if, while, etc.
This rule is inspired by the explicit-length-check rule from the unicorn ESLint plugin.