sindresorhus/eslint-plugin-unicorn
Rule proposal: `prefer-array-find-last`
Closed
#2,245 opened on Dec 21, 2023
help wantednew rule
Repository metrics
- Stars
- (5,022 stars)
- PR merge metrics
- (Avg merge 1d 16h) (399 merged PRs in 30d)
Description
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;
}
}