Skip to content

Commit

Permalink
feat(keep-sorted): support destructuring assignment (#11)
Browse files Browse the repository at this point in the history
Co-authored-by: Stephen Zhou <hi@hyoban.cc>
  • Loading branch information
antfu and hyoban authored May 6, 2024
1 parent 24e5ed5 commit c1cb519
Show file tree
Hide file tree
Showing 2 changed files with 80 additions and 1 deletion.
68 changes: 67 additions & 1 deletion src/commands/keep-sorted.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ run(
'apple',
'bar',
'foo',
]`,
]`
,
// Object property
{
code: $`
Expand Down Expand Up @@ -130,6 +131,7 @@ run(
errors: ['command-fix'],
},
{
description: 'Function arguments',
code: $`
function foo() {
// @keep-sorted
Expand Down Expand Up @@ -170,6 +172,24 @@ run(
}`,
errors: ['command-fix'],
},
{
description: 'Export statement without trailing comma',
code: $`
// @keep-sorted
export {
foo,
bar,
apple
}`,
output: $`
// @keep-sorted
export {
apple,
bar,
foo,
}`,
errors: ['command-fix'],
},
{
description: 'Sort array of objects',
code: $`
Expand Down Expand Up @@ -206,6 +226,52 @@ run(
]`,
errors: ['command-error'],
},
{
description: 'Destructuring assignment',
code: $`
// @keep-sorted
const { foo, bar, apple } = obj`,
output: $`
// @keep-sorted
const { apple, bar, foo, } = obj`,
errors: ['command-fix'],
},
{
description: 'Destructuring assignment multiple lines',
code: $`
// @keep-sorted
const {
foo,
bar,
apple,
} = obj`,
output: $`
// @keep-sorted
const {
apple,
bar,
foo,
} = obj`,
errors: ['command-fix'],
},
{
description: 'Destructuring assignment multiple lines without trailing comma',
code: $`
// @keep-sorted
const {
foo,
bar,
apple
} = obj`,
output: $`
// @keep-sorted
const {
apple,
bar,
foo,
} = obj`,
errors: ['command-fix'],
},
{
description: 'Block comment',
code: $`
Expand Down
13 changes: 13 additions & 0 deletions src/commands/keep-sorted.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ export const keepSorted: Command = {

const node = ctx.findNodeBelow(
'ObjectExpression',
'ObjectPattern',
'ArrayExpression',
'TSInterfaceBody',
'TSTypeLiteral',
Expand Down Expand Up @@ -53,6 +54,18 @@ export const keepSorted: Command = {
},
)
}
else if (node.type === 'ObjectPattern') {
sort(
ctx,
node,
node.properties,
(prop) => {
if (prop.type === 'Property')
return getString(prop.key)
return null
},
)
}
else if (node.type === 'ArrayExpression') {
return sort(
ctx,
Expand Down

0 comments on commit c1cb519

Please sign in to comment.