Skip to content

Latest commit

 

History

History
186 lines (132 loc) · 3.44 KB

explicit-length-check.md

File metadata and controls

186 lines (132 loc) · 3.44 KB

Enforce explicitly comparing the length or size property of a value

💼 This rule is enabled in the ✅ recommended config.

🔧💡 This rule is automatically fixable by the --fix CLI option and manually fixable by editor suggestions.

Enforce explicitly checking the length of an object and enforce the comparison style.

This rule is fixable, unless it's unsafe to fix.

Zero comparisons

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

Fail

const isEmpty = !foo.length;
const isEmpty = foo.length == 0;
const isEmpty = foo.length < 1;
const isEmpty = 0 === foo.length;
const isEmpty = 0 == foo.length;
const isEmpty = 1 > foo.length;
// Negative style is disallowed too
const isEmpty = !(foo.length > 0);
const isEmptySet = !foo.size;
<template>
	<div v-if="foo.length">Vue</div>
</template>

Pass

const isEmpty = foo.length === 0;
<template>
	<div v-if="foo.length > 0">Vue</div>
</template>

Non-zero comparisons

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

Fail

const isNotEmpty = foo.length !== 0;
const isNotEmpty = foo.length != 0;
const isNotEmpty = foo.length >= 1;
const isNotEmpty = 0 !== foo.length;
const isNotEmpty = 0 != foo.length;
const isNotEmpty = 0 < foo.length;
const isNotEmpty = 1 <= foo.length;
const isNotEmpty = Boolean(foo.length);
// Negative style is disallowed too
const isNotEmpty = !(foo.length === 0);
if (foo.length || bar.length) {}
const unicorn = foo.length ? 1 : 2;
while (foo.length) {}
do {} while (foo.length);
for (; foo.length; ) {};

Pass

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

Options

You can define your preferred way of checking non-zero length by providing a non-zero option (greater-than by default):

{
	'unicorn/explicit-length-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.length > 0
  • not-equal
    • Enforces non-zero to be checked with: foo.length !== 0

Unsafe to fix case

.length check inside LogicalExpressions are not safe to fix.

Example:

const bothNotEmpty = (a, b) => a.length && b.length;

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.length > 0 && b.length > 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.