Skip to content

useFind

¥Summary

¥How to configure

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

¥Description

强制使用 Array.prototype.find() 而不是 Array.prototype.filter() 后跟 [0] 来查找单个结果。

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

在查找数组中符合条件的第一个元素时,可能会想使用类似 arr.filter(x => x > 0)[0] 的代码。不过,使用 Array.prototype.find() 而不是 arr.find(x => x > 0) 会更简单,后者也能返回第一个符合条件的条目。由于 .find() 只需执行回调直到找到匹配项,因此效率更高。

¥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.

¥Examples

¥Invalid

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

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

¥Related links