Skip to content

Latest commit

Β 

History

History
49 lines (31 loc) Β· 2.46 KB

prefer-iterator-helpers.md

File metadata and controls

49 lines (31 loc) Β· 2.46 KB

prefer-iterator-helpers

πŸ“ Prefer iterator helpers over temporary arrays from iterators.

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

πŸ’‘ This rule is manually fixable by editor suggestions.

Prefer calling iterator helpers before converting an iterator to an array. Bounded .take() calls can avoid unnecessary consumption. Using only .drop() still exhausts the iterator, but avoids storing the discarded prefix.

Examples

// ❌
[...map.values()].find(value => value.id === id);

// βœ…
map.values().find(value => value.id === id);
// ❌
iterator.toArray().slice(20, 30);

// βœ…
iterator.drop(20).take(10).toArray();
// ❌
[...text.matchAll(pattern)].slice(0, 10);

// βœ…
text.matchAll(pattern).take(10).toArray();

The rule recognizes .values(), .keys(), .entries(), .matchAll(), static Iterator methods, lazy helper chains, and supported TypeScript iterator types. Slice conversions also treat a zero-argument .toArray() as iterator evidence. Custom methods matched by name must support iterator helpers. Arbitrary iterables are ignored because not every iterable has those methods.

Terminal conversions support .every(), .find(), .forEach(), .reduce(), and .some() after a single-spread array or one-argument Array.from(). Callbacks that can observe the extra array argument are ignored, whether they are inline or a reference whose declaration is in the same file. A reference that cannot be resolved here is treated as observing it.

Slice conversions support .slice() directly after .toArray(), a single-spread array, or one-argument Array.from(). Bounds must be statically known nonnegative safe integers. Copy-only .slice() and .slice(0) are ignored.

Calls are ignored when a suggestion would remove their type arguments.

Changes are offered as suggestions because callbacks and iterator consumption can behave differently. In particular, .take() can skip later side effects or errors and close the iterator early. Comments that cannot be preserved prevent a suggestion.

The rule does not report .filter(), .map(), or .flatMap() because their iterator versions return iterators. See prefer-iterator-to-array-at-end for those methods.