Skip to content

Latest commit

Β 

History

History
89 lines (64 loc) Β· 2.56 KB

File metadata and controls

89 lines (64 loc) Β· 2.56 KB

prefer-set-has

πŸ“ Prefer Set#has() over Array#includes() when checking for existence or non-existence.

πŸ’Ό This rule is enabled in the following configs: βœ… recommended, β˜‘οΈ unopinionated.

πŸ”§πŸ’‘ This rule is automatically fixable by the --fix CLI option and manually fixable by editor suggestions.

Set#has() is faster than Array#includes().

Examples

// ❌
const array = [1, 2, 3];
const hasValue = value => array.includes(value);

// βœ…
const set = new Set([1, 2, 3]);
const hasValue = value => set.has(value);

Arrays with supported extra references can also be converted when they have more than one includes() lookup. The array must be a plain literal with only unique, statically known primitive or null values, and no holes, spreads, or -0.

Supported extra references are for…of, array spread, call or constructor argument spread, .length, and .forEach() with a one-parameter arrow function.

// ❌
const array = [1, 2, 3];
for (const item of array) {
	console.log(item);
}

const length = array.length;
const hasValue = value => array.includes(value);

// βœ…
const set = new Set([1, 2, 3]);
for (const item of set) {
	console.log(item);
}

const length = set.size;
const hasValue = value => set.has(value);
// βœ…
// This array has a usage that does not work the same on a `Set`.
const array = [1, 2];
const hasValue = value => array.includes(value);
array.push(3);
// βœ…
// This array is only checked once.
const array = [1, 2, 3];
const hasOne = array.includes(1);

Options

Type: object

minimumItems

Type: integer
Minimum: 0
Default: 0

The minimum known array size before Set#has() is enforced.

When this option is greater than 0, this rule only reports arrays with a statically known size.

/* eslint unicorn/prefer-set-has: ["error", {"minimumItems": 5}] */

// ❌
const array = [1, 2, 3, 4, 5];
const hasValue = value => array.includes(value);

// βœ…
const smallArray = [1, 2, 3, 4];
const hasSmallValue = value => smallArray.includes(value);