-
-
Notifications
You must be signed in to change notification settings - Fork 4.4k
/
no-object-constructor.js
102 lines (80 loc) · 3.09 KB
/
no-object-constructor.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
/**
* @fileoverview Rule to disallow calls to the `Object` constructor without an argument
* @author Francesco Trotta
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const { getVariableByName, isArrowToken } = require("./utils/ast-utils");
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../shared/types').Rule} */
module.exports = {
meta: {
type: "suggestion",
docs: {
description: "Disallow calls to the `Object` constructor without an argument",
recommended: false,
url: "https://eslint.org/docs/latest/rules/no-object-constructor"
},
hasSuggestions: true,
schema: [],
messages: {
preferLiteral: "The object literal notation {} is preferable.",
useLiteral: "Replace with '{{replacement}}'."
}
},
create(context) {
const sourceCode = context.sourceCode;
/**
* Determines whether or not an object literal that replaces a specified node needs to be enclosed in parentheses.
* @param {ASTNode} node The node to be replaced.
* @returns {boolean} Whether or not parentheses around the object literal are required.
*/
function needsParentheses(node) {
let exprStatNode = node;
while (exprStatNode && exprStatNode.type !== "ExpressionStatement") {
exprStatNode = exprStatNode.parent;
}
if (exprStatNode && node.range[0] === exprStatNode.range[0]) {
return true;
}
const prevToken = sourceCode.getTokenBefore(node);
if (prevToken && isArrowToken(prevToken)) {
return true;
}
return false;
}
/**
* Reports on nodes where the `Object` constructor is called without arguments.
* @param {ASTNode} node The node to evaluate.
* @returns {void}
*/
function check(node) {
if (node.callee.name !== "Object" || node.arguments.length) {
return;
}
const variable = getVariableByName(sourceCode.getScope(node), "Object");
if (variable && variable.identifiers.length === 0) {
const replacement = needsParentheses(node) ? "({})" : "{}";
context.report({
node,
messageId: "preferLiteral",
suggest: [
{
messageId: "useLiteral",
data: { replacement },
fix: fixer => fixer.replaceText(node, replacement)
}
]
});
}
}
return {
CallExpression: check,
NewExpression: check
};
}
};