Skip to content

Commit

Permalink
refactor: handle edgecases
Browse files Browse the repository at this point in the history
  • Loading branch information
sasial-dev committed Nov 29, 2024
1 parent 6bcf36d commit c819370
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 4 deletions.
26 changes: 22 additions & 4 deletions src/rules/sort-collections.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,12 @@ export const rule = createRule<Options>({
toSort.includes(key.value)
) {
const currentOrder = collection.properties;
const scripts = new Set(
currentOrder.map(
(prop) => (prop.key as AST.JSONStringLiteral).value,
),
);

const desiredOrder = currentOrder.slice().sort((a, b) => {
let aKey = (a.key as AST.JSONStringLiteral).value;
let bKey = (b.key as AST.JSONStringLiteral).value;
Expand All @@ -38,18 +44,30 @@ export const rule = createRule<Options>({
} else {
let modifier = 0;

if (aKey.startsWith("pre")) {
if (
aKey.startsWith("pre") &&
scripts.has(aKey.substring(3))
) {
aKey = aKey.substring(3);
modifier -= 1;
} else if (aKey.startsWith("post")) {
} else if (
aKey.startsWith("post") &&
scripts.has(aKey.substring(4))
) {
aKey = aKey.substring(4);
modifier += 1;
}

if (bKey.startsWith("pre")) {
if (
bKey.startsWith("pre") &&
scripts.has(bKey.substring(3))
) {
bKey = bKey.substring(3);
modifier += 1;
} else if (bKey.startsWith("post")) {
} else if (
bKey.startsWith("post") &&
scripts.has(bKey.substring(4))
) {
bKey = bKey.substring(4);
modifier -= 1;
}
Expand Down
24 changes: 24 additions & 0 deletions src/tests/rules/sort-collections.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,5 +112,29 @@ ruleTester.run("sort-collections", rule, {
filename: "not-a-package.json",
options: [["devDependencies"]],
},
{
code: `{
"scripts": {
"lint": "echo test",
"poster": "echo test"
}
}`,
},
{
code: `{
"scripts": {
"pretest": "echo test",
"watch": "echo test"
}
}`,
},
{
code: `{
"scripts": {
"postwatch": "echo test",
"pretest": "echo test"
}
}`,
},
],
});

0 comments on commit c819370

Please sign in to comment.