Skip to content

Latest commit

 

History

History
173 lines (125 loc) · 3.26 KB

File metadata and controls

173 lines (125 loc) · 3.26 KB

Enforce explicitly comparing the size property of a value

🔧💡 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.

Zero comparisons

Enforce comparison with === 0 when checking for zero size.

Zero comparison failures

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();

Zero comparison successes

const isEmpty = foo.size() === 0;

Non-zero comparisons

Enforce comparison with > 0 when checking for non-zero size.

Non-zero comparison failures

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()) {}

Non-zero comparison successes

const isNotEmpty = foo.size() > 0;
if (foo.size() > 0 || bar.size() > 0) {
}

Options

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
  • not-equal
    • Enforces non-zero to be checked with: foo.size() !== 0

Unsafe to fix case

.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.

Credits

This rule is inspired by the explicit-length-check rule from the unicorn ESLint plugin.