-
Notifications
You must be signed in to change notification settings - Fork 0
/
prefer-spelling.js
112 lines (108 loc) · 3.95 KB
/
prefer-spelling.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
module.exports = {
meta: {
type: "suggestion",
docs: {
description: "Enforce preferred spelling of words",
category: "Stylistic Issues",
recommended: false,
},
fixable: "code",
schema: [
{
type: "object",
properties: {
words: {
type: "object",
additionalProperties: {
type: "string",
},
},
severity: {
enum: ["error", "warn", "info"],
},
},
additionalProperties: false,
},
],
},
create(context) {
const options = context.options[0] || {};
const words = options.words || {};
const reportedNodes = new Set();
function checkNode(node, value) {
if (reportedNodes.has(node)) {
return;
}
Object.entries(words).forEach(([incorrect, correct]) => {
const regex = new RegExp(`\\b\\w*${incorrect}\\w*\\b`, "gi");
const match = regex.exec(value);
if (match) {
const matchedWord = match[0];
context.report({
node,
message: `Use '{{correct}}' instead of '{{incorrect}}'.`,
data: {
correct: correct,
incorrect: incorrect,
},
fix(fixer) {
const replacement = matchedWord.replace(
new RegExp(incorrect, "gi"),
(match) => {
if (match === match.toLowerCase())
return correct.toLowerCase();
if (match === match.toUpperCase())
return correct.toUpperCase();
return (
correct[0].toUpperCase() +
correct.slice(1).toLowerCase()
);
}
);
if (node.type === "Literal") {
const newText =
value.slice(0, match.index) +
replacement +
value.slice(
match.index + matchedWord.length
);
return fixer.replaceText(node, `'${newText}'`);
} else {
return fixer.replaceText(node, replacement);
}
},
});
reportedNodes.add(node);
}
});
}
return {
Literal(node) {
if (typeof node.value === "string") {
checkNode(node, node.value);
}
},
Identifier(node) {
checkNode(node, node.name);
},
FunctionDeclaration(node) {
if (node.id) {
checkNode(node.id, node.id.name);
}
},
FunctionExpression(node) {
if (node.id) {
checkNode(node.id, node.id.name);
}
},
ArrowFunctionExpression(node) {
if (
node.parent.type === "VariableDeclarator" &&
node.parent.id
) {
checkNode(node.parent.id, node.parent.id.name);
}
},
};
},
};