Przejdź do głównej zawartości

useFind

Ta treść nie jest jeszcze dostępna w Twoim języku.

biome.json
{
"linter": {
"rules": {
"nursery": {
"useFind": "error"
}
}
}
}

Enforce the use of Array.prototype.find() over Array.prototype.filter() followed by [0] when looking for a single result.

When searching for the first item in an array matching a condition, it may be tempting to use code like arr.filter(x => x > 0)[0]. However, it is simpler to use Array.prototype.find() instead, arr.find(x => x > 0), which also returns the first entry matching a condition. Because the .find() only needs to execute the callback until it finds a match, it’s also more efficient.

invalid.ts
[1, 2, 3].filter(x => x > 1)[0];
/invalid.ts:1:1 lint/nursery/useFind ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Prefer using Array#find() over Array#filter[0].

> 1 │ [1, 2, 3].filter(x => x > 1)[0];
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2 │

Use Array#find() instead of Array#filter[0] to improve readability.

invalid2.ts
[1, 2, 3].filter(x => x > 1).at(0);
/invalid2.ts:1:1 lint/nursery/useFind ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Prefer using Array#find() over Array#filter[0].

> 1 │ [1, 2, 3].filter(x => x > 1).at(0);
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2 │

Use Array#find() instead of Array#filter[0] to improve readability.

valid.ts
[1, 2, 3].find(x => x > 1);