sindresorhus/eslint-plugin-unicorn

Rule proposal: `prefer-else-if`

Chiusa

#1393 aperta il 1 lug 2021

 (5 commenti) (1 reazione) (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

Fail

if (foo === '1') {
  // ...
}
if (foo === '2') {
  // ...
}

Pass

function a() {
  if (foo === '1') {
    // ...
    return;
  }

  if (foo === '2') {
    // ...
    return;
  }
}
if (foo === '1') {
  // ...
} else if (foo === '2') {
  // ...
}
if (foo === '1') {
  ...
}
if (foo === '2') {
  ...
}
if (foo === '3') {
  ...
}
if (foo === '4') {
  ...
}

To fix this case, we can simply only check if foo is declared as const.

This come from my work, but real case is more complicated, it's like

if (foo.bar === '1') {
  ...
}
if (foo.bar === '2') {
  ...
}
if (foo.bar === '3') {
  ...
}
if (foo.bar === '4') {
  ...
}

To fix this case, we need to check foo.bar and foo didn't get changed in each if block, I feel this is hard (even impossible) to do.

Guida contributor