sindresorhus/eslint-plugin-unicorn

Rule proposal: `prefer-array-find-last`

Chiusa

#2245 aperta il 21 dic 2023

 (1 commento) (0 reazioni) (0 assegnatari)JavaScript (468 fork)user submission
help wantednew rule

Metriche repository

Star
 (5022 stelle)
Metriche merge PR
 (Merge medio 1g 16h) (399 PR mergiate in 30 g)

Descrizione

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;
  }
}

Guida contributor