Skip to content

Commit f4031e1

Browse files
committed
spread
1 parent 2b1eee1 commit f4031e1

File tree

2 files changed

+40
-8
lines changed

2 files changed

+40
-8
lines changed

rules/vue-sort-components.js

Lines changed: 28 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,29 @@ const naturalCompare = require("natural-compare");
1010
const getKeyName = (node) =>
1111
node.key.type === "Identifier" ? node.key.name : "";
1212

13+
/**
14+
* @param {import('estree').Expression} arg
15+
* @returns {string}
16+
*/
17+
const getArgName = (arg) => (arg.type === "Identifier" ? arg.name : "");
18+
19+
/**
20+
* @param {import('estree').Property | import('estree').SpreadElement} a
21+
* @param {import('estree').Property | import('estree').SpreadElement} b
22+
* @returns {-1 | 0 | 1}
23+
*/
24+
const compareNodes = (a, b) => {
25+
if (a.type === "Property" && b.type === "Property") {
26+
return naturalCompare(getKeyName(a), getKeyName(b));
27+
}
28+
29+
if (a.type === "SpreadElement" && b.type === "SpreadElement") {
30+
return naturalCompare(getArgName(a.argument), getArgName(b.argument));
31+
}
32+
33+
return a.type === "SpreadElement" ? -1 : 1;
34+
};
35+
1336
/** @type {import('eslint').Rule.RuleModule} */
1437
module.exports = {
1538
meta: {
@@ -30,16 +53,13 @@ module.exports = {
3053
return;
3154
}
3255

33-
const properties = value.properties.filter(
34-
/** @returns {node is import('estree').Property} */
35-
(node) => node.type === "Property"
36-
);
37-
const sorted = [...properties].sort((a, b) =>
38-
naturalCompare(getKeyName(a), getKeyName(b))
39-
);
56+
const properties = value.properties;
57+
const sorted = [...properties].sort(compareNodes);
4058
const sameOrder = properties.every((v, i) => v === sorted[i]);
4159

42-
if (sameOrder) return;
60+
if (sameOrder) {
61+
return;
62+
}
4363

4464
context.report({
4565
node,

tests/vue-sort-components.spec.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,11 @@ ruleTester.run("vue-sort-components", rule, {
2828
code: "const obj = { nested: { components: { bar, baz, foo } } }",
2929
parserOptions: { ecmaVersion: 6 },
3030
},
31+
// spread
32+
{
33+
code: "const obj = { components: { ...others, bar, baz, foo } }",
34+
parserOptions: { ecmaVersion: 2018 },
35+
},
3136
// not components
3237
{
3338
code: "const obj = { nested: { foo, bar } }",
@@ -61,5 +66,12 @@ ruleTester.run("vue-sort-components", rule, {
6166
parserOptions: { ecmaVersion: 6 },
6267
errors: [{ messageId: "sortComponents" }],
6368
},
69+
// spread
70+
{
71+
code: "const obj = { components: { bar, ...others, foo, ...others2 } }",
72+
output: "const obj = { components: { ...others, ...others2, bar, foo } }",
73+
parserOptions: { ecmaVersion: 2018 },
74+
errors: [{ messageId: "sortComponents" }],
75+
},
6476
],
6577
});

0 commit comments

Comments
 (0)