sindresorhus/eslint-plugin-unicorn

Rule proposal: `prefer-else-if`

Closed

#1,393 opened on Jul 1, 2021

 (5 comments) (1 reaction) (0 assignees)JavaScript (468 forks)user submission
help wantednew rule

Repository metrics

Stars
 (5,022 stars)
PR merge metrics
 (Avg merge 1d 16h) (399 merged PRs in 30d)

Description

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.

Contributor guide