Skip to content

Latest commit

Β 

History

History
72 lines (53 loc) Β· 2.1 KB

File metadata and controls

72 lines (53 loc) Β· 2.1 KB

prefer-direct-iteration

πŸ“ Prefer direct iteration over default iterator method calls.

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

πŸ”§ This rule is automatically fixable by the --fix CLI option.

Some built-ins expose their default iterator through both [Symbol.iterator]() and a named method. For example, Map#entries() is the same iterator as Map#[Symbol.iterator](), and Array#values() is the same iterator as Array#[Symbol.iterator]().

When the result is immediately consumed as an iterable, the named method is redundant.

This rule reports:

  • .entries() for Map, FormData, and URLSearchParams
  • .values() for Array, typed arrays, and Set
  • .keys() for Set

It intentionally does not report unknown receivers, or methods that are not equivalent to the default iterator, such as Array#entries(), Map#values(), or Set#entries().

With TypeScript type information, this rule can also recognize supported built-ins through type aliases and inferred references. Without type information, it only uses direct syntax and simple annotations.

Examples

// ❌
const map = new Map();
for (const entry of map.entries()) {}
// βœ…
const map = new Map();
for (const entry of map) {}
// ❌
const array = [1, 2, 3];
const values = [...array.values()];
// βœ…
const array = [1, 2, 3];
const values = [...array];
// ❌
const map = new Map();
const copy = new Map(map.entries());
// βœ…
const map = new Map();
const copy = new Map(map);
// βœ… β€” `Array#entries()` yields `[index, value]` pairs, while arrays iterate values by default
for (const entry of array.entries()) {}
// βœ… β€” unknown receiver
for (const item of collection.values()) {}