snowcoders / sortier

An opinionated code sorter
https://snowcoders.github.io/sortier/
MIT License
30 stars 2 forks source link

Typescript enums not sorted #1820

Open mohammadalipak opened 2 years ago

mohammadalipak commented 2 years ago

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 commented 2 years ago

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 commented 2 years ago

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