azat-io / eslint-plugin-perfectionist

🦄 ESLint plugin for sorting various data such as objects, imports, types, enums, JSX props, etc.
https://eslint-plugin-perfectionist.azat.io
MIT License
1.64k stars 29 forks source link

Feature: Context-aware Rules #148

Open kitschpatrol opened 2 weeks ago

kitschpatrol commented 2 weeks ago

What rule do you want to change?

perfectionist/sort-objects

Describe the problem

This not strictly limited to the /sort-objects rule, but I'll use it as an example.

Often, the most intuitive ordering is contingent on the other keys present in an object.

For example if an object is intended to represent a color or a quaternion, alphabetical or natural sorting doesn't align with convention.

It's challenging to describe these context-driven rules using groups and custom-groups without interfering with more general cases, since each key is considered atomically.

Code example

Natural or alphabetical sort is makes sense in most cases:

const multipleChoice = {
    a: true,
    b: false,
    c: false
};

But the canonical ordering of certain data structures is different, for example:

// Desired:
const quaternion = {
    x: 0, 
    y: 0,
    z: 0,
    w: 0
};

// Perfectionist:
const quaternion = {
    w: 0
    x: 0, 
    y: 0,
    z: 0,
};

Or:

// Desired:
const color = {
    r: 0.8,
    g: 0.5,
    b: 0.5,
    a: 0.25
};

// Perfectionist:
const color = {
    a: 0.25
    b: 0.5,
    g: 0.5,
    r: 0.8,
};

I've come up with a rather sketchy rule configuration that can cover the quaternion and color and a couple other cases, but still ends up breaking in the multipleChoice case... but can't figure out how to cover all cases without some awareness of the what the entire set of keys to be sorted is.

Additional comments

I'm not sure what the best way to expose this functionality might be, perhaps groups could become a record of arrays keyed with some kind of predicate that is run over each key in the object to identify if it's a candidate for a particular group of sorting rules.

It's also possible I'm just missing something about the possibilities already available through groups and custom-groups.

Thanks for a great tool.

Validations