-
Notifications
You must be signed in to change notification settings - Fork 16
/
no-unnecessary-duplication.js
116 lines (107 loc) · 2.97 KB
/
no-unnecessary-duplication.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
const {
extractImportedFromEffector,
} = require("../../utils/extract-imported-from-effector");
const { areNodesSameInText } = require("../../utils/are-nodes-same-in-text");
module.exports = {
meta: {
type: "problem",
docs: {
description: "Forbids unnecessary duplication in `clock` and `source`",
category: "Quality",
recommended: true,
},
messages: {
unnecessaryDuplication:
"Same `source` and `clock` can be replaced with only one of them.",
removeClock: "Remove `clock`",
removeSource: "Remove `source`",
},
schema: [],
},
create(context) {
const importedFromEffector = new Map();
const sourceCode = context.getSourceCode();
return {
ImportDeclaration(node) {
extractImportedFromEffector(importedFromEffector, node);
},
CallExpression(node) {
const METHODS_WITH_POSSIBLE_DUPLCATION = ["sample", "guard"];
for (const method of METHODS_WITH_POSSIBLE_DUPLCATION) {
const localMethod = importedFromEffector.get(method);
if (!localMethod) {
continue;
}
const isEffectorMethod = node?.callee?.name === localMethod;
if (!isEffectorMethod) {
continue;
}
const params = {
source: node?.arguments?.[0]?.properties?.find(
(n) => n.key.name === "source"
),
clock: node?.arguments?.[0]?.properties?.find(
(n) => n.key.name === "clock"
),
};
if (!params.source || !params.clock) {
return;
}
const sameSourceAndClock = areNodesSameInText({
context,
nodes: [params.source?.value, params.clock?.value],
});
if (!sameSourceAndClock) {
return;
}
reportUnnecessaryDuplication({
context,
node,
params,
firstArgument: node?.arguments?.[0],
});
}
},
};
},
};
function reportUnnecessaryDuplication({
context,
node,
params,
firstArgument,
}) {
function excludeParamFromObjectInText(objectNode, paramToExcludeNode) {
const properties = objectNode?.properties?.filter?.(
(p) => p !== paramToExcludeNode
);
const newPropertiesText = properties
.map((p) => context.getSourceCode().getText(p))
.join(", ");
return `{ ${newPropertiesText} }`;
}
context.report({
node,
messageId: "unnecessaryDuplication",
suggest: [
{
messageId: "removeClock",
fix(fixer) {
return fixer.replaceText(
firstArgument,
excludeParamFromObjectInText(firstArgument, params.clock)
);
},
},
{
messageId: "removeSource",
fix(fixer) {
return fixer.replaceText(
firstArgument,
excludeParamFromObjectInText(firstArgument, params.source)
);
},
},
],
});
}