sindresorhus/eslint-plugin-unicorn
Rule proposal: `prefer-array-find-last`
クローズ
#2,245 opened on 2023/12/21
help wantednew rule
Repository metrics
- Stars
- (5,022 個のスター)
- PR merge metrics
- (平均マージ 4h 30m) (30d で 26 merged PRs)
説明
Description
Array#findLast is available now in Node.js 18.
Fail
function foo(array, callback) {
for (let index = array.length - 1; index >= 0; index--) {
const element = array[index];
if (callback(element, index, array)) {
return element;
}
}
}
let foo;
for (let index = array.length - 1; index >= 0; index--) {
const element = array[index];
if (callback(element, index, array)) {
foo = element;
break;
}
}
Pass
array.findLast(callback);
Additional Info
This rule will be difficult to implement.
First, there are too many things in JavaScript that have .length, we can't know the type of looping object.
Second, even if we assume they are all arrays, we still can only fix very few cases.
function foo(array, callback) {
for (let index = array.length - 1; index >= 0; index--) {
const element = array[index];
if (callback(element, index, array)) {
return element;
}
}
return somethingNotUndefiend; // This makes the case unfixable.
}
function foo(array, callback) {
for (let index = array.length - 1; index >= 0; index--) {
const element = array[index];
if (callback(element, index, array)) {
return element;
}
}
// Any additional code after this makes the case unfixable.
// Code handles not found case.
}
let foo = somethingNotUndefiend; // This makes the case unfixable.
for (let index = array.length - 1; index >= 0; index--) {
const element = array[index];
if (callback(element, index, array)) {
foo = element;
break;
}
}