Skip to content

Commit

Permalink
refactor: optimize code
Browse files Browse the repository at this point in the history
  • Loading branch information
chouchouji committed Jan 20, 2025
1 parent d1af287 commit 9608e37
Showing 1 changed file with 41 additions and 37 deletions.
78 changes: 41 additions & 37 deletions src/rules/no-empty-fields.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,60 +2,64 @@ import type { AST as JsonAST } from "jsonc-eslint-parser";

import * as ESTree from "estree";

import { createRule } from "../createRule";
import { createRule, PackageJsonRuleContext } from "../createRule";

export const rule = createRule({
create(context) {
const report = (node: JsonAST.JSONProperty) => {
context.report({
data: { field: (node.key as JsonAST.JSONStringLiteral).value },
messageId: "emptyFields",
node: node as unknown as ESTree.Node,
suggest: [
{
*fix(fixer) {
yield fixer.remove(node as unknown as ESTree.Node);
const report = (
context: PackageJsonRuleContext,
node: JsonAST.JSONProperty,
) => {
context.report({
data: { field: (node.key as JsonAST.JSONStringLiteral).value },
messageId: "emptyFields",
node: node as unknown as ESTree.Node,
suggest: [
{
*fix(fixer) {
yield fixer.remove(node as unknown as ESTree.Node);

const tokenFromCurrentLine =
context.sourceCode.getTokenAfter(
node as unknown as ESTree.Node,
);
const tokenFromPreviousLine =
context.sourceCode.getTokenBefore(
node as unknown as ESTree.Node,
);
const tokenFromCurrentLine =
context.sourceCode.getTokenAfter(
node as unknown as ESTree.Node,
);
const tokenFromPreviousLine =
context.sourceCode.getTokenBefore(
node as unknown as ESTree.Node,
);

if (
tokenFromPreviousLine?.value === "," &&
tokenFromCurrentLine?.value !== ","
) {
yield fixer.remove(tokenFromPreviousLine);
}
if (
tokenFromPreviousLine?.value === "," &&
tokenFromCurrentLine?.value !== ","
) {
yield fixer.remove(tokenFromPreviousLine);
}

if (tokenFromCurrentLine?.value === ",") {
yield fixer.remove(tokenFromCurrentLine);
}
},
messageId: "remove",
},
],
});
};
if (tokenFromCurrentLine?.value === ",") {
yield fixer.remove(tokenFromCurrentLine);
}
},
messageId: "remove",
},
],
});
};

export const rule = createRule({
create(context) {
return {
JSONArrayExpression(node: JsonAST.JSONArrayExpression) {
if (
!node.elements.length &&
node.parent.type === "JSONProperty"
) {
report(node.parent);
report(context, node.parent);
}
},
JSONObjectExpression(node: JsonAST.JSONObjectExpression) {
if (
!node.properties.length &&
node.parent.type === "JSONProperty"
) {
report(node.parent);
report(context, node.parent);
}
},
};
Expand Down

0 comments on commit 9608e37

Please sign in to comment.