Conversation
|
|
||
| return { | ||
| Object(node) { | ||
| const hasUnsafeComments = |
There was a problem hiding this comment.
This variable hasUnsafeComments should be moved inside the fix as it is only needed then and it should be specific to the members being swapped.
In the following example it is safe to swap "b" and "c":
{
// Comment for a
"a": true,
"c": false,
"b": false
}.There was a problem hiding this comment.
I thought about this case as well, but reliably detecting only safe cases like this requires non-trivial comment association logic, and it’s easy to get wrong. So I’m not sure it’s worth adding that complexity.
There was a problem hiding this comment.
You can use sourceCode.getTokenBefore/After with includeComments: true for each property and then do not fix if one of the four tokens is a comment (for getTokenAfter make sure that you skip commas with a filter):
const commentTypes = new Set(['LineComment', 'BlockComment']);
function hasComment(member, sourceCode) {
const before = sourceCode.getTokenBefore(member, { includeComments: true });
const after = sourceCode.getTokenAfter(member, { includeComments: true, filter: ({ type }) => type === ',');
return commentTypes.has(before.type) || commentTypes.has(after.type);
}| for (const member of node.members) { | ||
| const thisName = getKey(member); | ||
| const thisRawName = getRawKey(member, sourceCode); | ||
| const prevMemberNode = prevMember; |
There was a problem hiding this comment.
This alias (prevMemberNode = prevMember) is unnecessary as fixes are eagerly executed (you can replace the references of prevMemberNode with just prevMember).
There was a problem hiding this comment.
That alias is intentional. Without it, ESLint reports a no-loop-func error (Function declared in a loop contains unsafe references to variable(s) 'prevMember')
There was a problem hiding this comment.
Oh okay, personally I would prefer an eslint-ignore as this is a workaround which trips up developers reading the code.
I don't feel strongly either way but can you please add a comment explaining why the alias exists?
Prerequisites checklist
AI acknowledgment
What is the purpose of this pull request?
This PR adds autofix support to
sort-keysso eslint can automatically reorder object keys, while avoiding fixes that could detach/misplace comments.What changes did you make? (Give an overview)
sort-keysas fixable and implemented a fixer that swaps out-of-order adjacent members.Related Issues
Fixes #122
Is there anything you'd like reviewers to focus on?