Skip to content

Commit

Permalink
fix: do not report on shadowed constructors in no-new-wrappers (#17447
Browse files Browse the repository at this point in the history
)

* fix: do not report on shadowed constructors in `no-new-wrappers`

* unit tests for undefined constructors
  • Loading branch information
fasttime committed Aug 9, 2023
1 parent 757bfe1 commit 631648e
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 8 deletions.
26 changes: 19 additions & 7 deletions lib/rules/no-new-wrappers.js
Expand Up @@ -5,6 +5,12 @@

"use strict";

//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------

const { getVariableByName } = require("./utils/ast-utils");

//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
Expand All @@ -28,18 +34,24 @@ module.exports = {
},

create(context) {
const { sourceCode } = context;

return {

NewExpression(node) {
const wrapperObjects = ["String", "Number", "Boolean"];

if (wrapperObjects.includes(node.callee.name)) {
context.report({
node,
messageId: "noConstructor",
data: { fn: node.callee.name }
});
const { name } = node.callee;

if (wrapperObjects.includes(name)) {
const variable = getVariableByName(sourceCode.getScope(node), name);

if (variable && variable.identifiers.length === 0) {
context.report({
node,
messageId: "noConstructor",
data: { fn: name }
});
}
}
}
};
Expand Down
49 changes: 48 additions & 1 deletion tests/lib/rules/no-new-wrappers.js
Expand Up @@ -21,7 +21,36 @@ const ruleTester = new RuleTester();
ruleTester.run("no-new-wrappers", rule, {
valid: [
"var a = new Object();",
"var a = String('test'), b = String.fromCharCode(32);"
"var a = String('test'), b = String.fromCharCode(32);",
`
function test(Number) {
return new Number;
}
`,
{
code: `
import String from "./string";
const str = new String(42);
`,
parserOptions: { ecmaVersion: 6, sourceType: "module" }
},
`
if (foo) {
result = new Boolean(bar);
} else {
var Boolean = CustomBoolean;
}
`,
{
code: "new String()",
globals: {
String: "off"
}
},
`
/* global Boolean:off */
assert(new Boolean);
`
],
invalid: [
{
Expand Down Expand Up @@ -53,6 +82,24 @@ ruleTester.run("no-new-wrappers", rule, {
},
type: "NewExpression"
}]
},
{
code: `
const a = new String('bar');
{
const String = CustomString;
const b = new String('foo');
}
`,
parserOptions: { ecmaVersion: 6 },
errors: [{
messageId: "noConstructor",
data: {
fn: "String"
},
type: "NewExpression",
line: 2
}]
}
]
});

0 comments on commit 631648e

Please sign in to comment.