eslint-plugin-perfectionist icon indicating copy to clipboard operation
eslint-plugin-perfectionist copied to clipboard

Feature: (sort-switch-case) Would you consider sorting the `case` blocks in a `switch` statement?

Open u3u opened this issue 2 years ago • 3 comments

Describe the rule

Can you add a sort-switch-case rule? It will sort the case statements, their order does not affect the execution result, but it can improve readability, reduce code merge conflicts, and eliminate the need to worry about their order when writing code.

Code example

Input

switch (type) {
  case 'save': {
    break;
  }

  case 'edit': {
    break;
  }

  default:
  case 'close': {
    break;
  }
}

Output

switch (type) {
  default:
  case 'close': {
    break;
  }

  case 'edit': {
    break;
  }

  case 'save': {
    break;
  }
}

Additional comments

No response

Validations

  • [X] Read the docs.
  • [X] Check that there isn't already an issue that reports the same bug to avoid creating a duplicate.

u3u avatar Aug 04 '23 14:08 u3u

That's a cool idea. I think we should add that.

azat-io avatar Aug 05 '23 12:08 azat-io

The form switch(true) will become more popular with the release of typescript 5.3 https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-3.html#switch-true-narrowing

That also makes this feature more difficult to implement if switching the order of cases causes type errors, but maybe that is just revealing a bug

Pyrolistical avatar Nov 30 '23 02:11 Pyrolistical

@Pyrolistical Yes, thank you for the comment. Safety is our priority.

azat-io avatar Nov 30 '23 14:11 azat-io

Thank you for your issue!

It was a great idea. If you have any more suggestions for improving the plugin, feel free to create a new issue.

This feature was implemented in 5311118ebea707e0b885c4cf6ecbd84d10ea08d2 and released in v3.0.0.

If you'd like, you can support the release with a retweet: https://x.com/azat_io_en/status/1815367279191761054

azat-io avatar Jul 22 '24 12:07 azat-io

image image image image

@azat-io Hi, thank you for implementing this!! but it seems that it cannot be used together with unicorn/switch-case-braces. And there is a slight issue with sorting when case and default are used together.

u3u avatar Aug 05 '24 06:08 u3u