Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Typescript enums not sorted #1820

Open
mohammadalipak opened this issue Oct 17, 2022 · 2 comments
Open

Typescript enums not sorted #1820

mohammadalipak opened this issue Oct 17, 2022 · 2 comments

Comments

@mohammadalipak
Copy link

Language

Typescript

Sample input source code

enum Fruit {
  WATERMELON = 'WATERMELON',
  APPLE = 'APPLE',
  BANANA = 'BANANA',
}

Expected output

enum Fruit {
  APPLE = 'APPLE',
  BANANA = 'BANANA',
  WATERMELON = 'WATERMELON',
}

Actual output

enum Fruit {
  WATERMELON = 'WATERMELON',
  APPLE = 'APPLE',
  BANANA = 'BANANA',
}

It seems like sortier ignores the Typescript enums. It should be sorting them by keys.

@k2snowman69
Copy link
Member

Hmmm interesting request which could work in some cases. The main case for enum is that you don't define anything:

enum Fruit {
  WATERMELON,
  APPLE,
  BANANA
}

https://www.typescriptlang.org/play?#code/KYOwrgtgBAYgTmAlgFygbwFBSgdQIIAqAogEoCyRAMgPIByANFlHgAouVGPYBCetfeKAF4oAcl79+oxgF8gA

in which case they are in order since enum assigns numbers in order.

We could technically sort keys with assigned values as long as they are adjacent:

enum Fruit {
  WATERMELON,
  BANANA = 'BANANA',
  APPLE = "APPLE",
}

As they wouldn't impact the inferred value provided to keys without values. This would resolve your ticket.

But to respond to your statement "It seems like sortier ignores the Typescript enums. It should be sorting them by keys." the answer is yes because without values, the order of an enum is crucial to it's generated value hence why it was ignored.

However you bring up a good point that if the values are defined, we should be able to change the order. Let me think on this to see if there are scenarios I'm missing.

@k2snowman69
Copy link
Member

I'd welcome a PR here, should be relatively straight forward:

  1. Create a folder under src\language-js or just copy an existing one like sortJsxElement and name it sortEnum
  2. Implement sorting enum values. Hint you can get the type EnumDeclaration from import { EnumDeclaration } from "typescript";.
  3. Implement a ridiculous number of tests (both scenarios I brought up above, context groups, comments, etc)
  4. Finally add it into src\language-js\reprinter\index.ts to hook up the enum sorting to execute via the cli or vscode

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants