Skip to content

Commit 9b2692c

Browse files
committed
feat(keep-sorted): support specify keys for sorting
1 parent c52a50d commit 9b2692c

File tree

4 files changed

+235
-110
lines changed

4 files changed

+235
-110
lines changed

README.md

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,32 @@ const obj = {
104104

105105
Different from the other commands, the comment will not be removed after transformation to keep the sorting.
106106

107+
#### Sort Array of Objects
108+
109+
This command takes an optional inline JSON configuration to specify the keys to sort.
110+
111+
```js
112+
/// keep-sorted { "keys": ["index", "name"] }
113+
const arr = [
114+
{ index: 4, name: 'foo' },
115+
{ index: 2, name: 'bar' },
116+
{ index: 2, name: 'apple' },
117+
{ index: 0, name: 'zip' },
118+
]
119+
```
120+
121+
Will be converted to:
122+
123+
```js
124+
/// keep-sorted { "keys": ["index", "name"] }
125+
const arr = [
126+
{ index: 0, name: 'zip' },
127+
{ index: 2, name: 'apple' },
128+
{ index: 2, name: 'bar' },
129+
{ index: 4, name: 'foo' },
130+
]
131+
```
132+
107133
### `to-for-each`
108134

109135
Convert for-of/for-in loop to `.forEach()`.

src/commands/keep-sorted.test.ts

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -172,4 +172,40 @@ run(
172172
}`,
173173
errors: ['command-fix'],
174174
},
175+
// Sort array of objects
176+
{
177+
code: d`
178+
// @keep-sorted { "keys": ["index", "name"] }
179+
export default [
180+
{ index: 4, name: 'foo' },
181+
{ index: 2, name: 'bar' },
182+
{ index: 2, name: 'apple' },
183+
{ index: 0, name: 'zip' },
184+
'foo',
185+
{ index: 6, name: 'bar' },
186+
{ index: 3, name: 'foo' },
187+
]`,
188+
output: d`
189+
// @keep-sorted { "keys": ["index", "name"] }
190+
export default [
191+
{ index: 0, name: 'zip' },
192+
{ index: 2, name: 'apple' },
193+
{ index: 2, name: 'bar' },
194+
{ index: 4, name: 'foo' },
195+
'foo',
196+
{ index: 3, name: 'foo' },
197+
{ index: 6, name: 'bar' },
198+
]`,
199+
errors: ['command-fix'],
200+
},
201+
// Error on invalid JSON
202+
{
203+
code: d`
204+
// @keep-sorted { keys: [1, 2, 3] }
205+
export default [
206+
{ index: 4, name: 'foo' },
207+
{ index: 2, name: 'bar' },
208+
]`,
209+
errors: ['command-error'],
210+
},
175211
)

0 commit comments

Comments
 (0)