/
no-instanceof-array.js
78 lines (69 loc) · 2.47 KB
/
no-instanceof-array.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
/**
* @author Toru Nagashima
* @copyright 2016 Toru Nagashima. All rights reserved.
* See LICENSE file in root directory for full license.
*/
"use strict"
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
module.exports = {
meta: {
docs: {
description: "disallow 'instanceof' for Array",
category: "Best Practices",
url: "https://github.com/mysticatea/eslint-plugin/blob/v13.0.0/docs/rules/no-instanceof-array.md",
},
fixable: "code",
schema: [],
type: "problem",
},
create(context) {
const sourceCode = context.getSourceCode()
/**
* Checks whether the given node is RHS of instanceof.
*
* @param {ASTNode} node - The node to check.
* @returns {boolean} `true` if the node is RHS of instanceof.
*/
function isRhsOfInstanceof(node) {
return (
node.parent.type === "BinaryExpression" &&
node.parent.operator === "instanceof" &&
node.parent.right === node
)
}
return {
"Program:exit"() {
const globalScope = context.getScope()
const variable = globalScope.set.get("Array")
// Skip if undefined or shadowed
if (variable == null || variable.defs.length > 0) {
return
}
for (const reference of variable.references) {
const id = reference.identifier
const node = id.parent
// Skip if it's not instanceof
if (!isRhsOfInstanceof(id)) {
continue
}
// Report
context.report({
node,
loc: node.loc,
message:
"Unexpected 'instanceof' operator. Use 'Array.isArray' instead.",
fix: (fixer) =>
fixer.replaceText(
node,
`Array.isArray(${sourceCode.getText(
node.left
)})`
),
})
}
},
}
},
}