Skip to content

Commit

Permalink
New: Let no-new-object pass with arguments (fixes eslint#11810)
Browse files Browse the repository at this point in the history
  • Loading branch information
brettz9 committed Jun 7, 2019
1 parent 21f3131 commit a5a238b
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 3 deletions.
23 changes: 23 additions & 0 deletions docs/rules/no-new-object.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,29 @@ var myObject = new CustomObject();
var myObject = {};
```

## Options

This rule has a single `allowWithArguments` option.

### allowWithArguments

One can coerce primitives into objects by passing `new Object()` an argument.
This option allows for this usage.

Examples of **incorrect** code for the `{ "allowWithArguments": true }` option:

```js
/*eslint no-new-object: [2, { "allowWithArguments": true }]*/
var myObject = new Object();
```

Examples of **correct** code for the `{ "allowWithArguments": true }` option:

```js
/*eslint no-new-object: [2, { "allowWithArguments": true }]*/
var myObject = new Object(BigInt('1'));
```

## When Not To Use It

If you wish to allow the use of the `Object` constructor, you can safely turn this rule off.
Expand Down
5 changes: 4 additions & 1 deletion lib/rules/no-new-object.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,14 @@ module.exports = {
},

create(context) {
const { allowWithArguments } = context.options[0] || {};

return {

NewExpression(node) {
if (node.callee.name === "Object") {
if (node.callee.name === "Object" && (
!allowWithArguments || !node.arguments.length
)) {
context.report({ node, message: "The object literal notation {} is preferrable." });
}
}
Expand Down
11 changes: 9 additions & 2 deletions tests/lib/rules/no-new-object.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,16 @@ const ruleTester = new RuleTester();

ruleTester.run("no-new-object", rule, {
valid: [
"var foo = new foo.Object()"
"var foo = new foo.Object()",
{
code: "var foo = new Object(BigInt('1n'))",
options: [
{ allowWithArguments: true }
]
}
],
invalid: [
{ code: "var foo = new Object()", errors: [{ message: "The object literal notation {} is preferrable.", type: "NewExpression" }] }
{ code: "var foo = new Object()", errors: [{ message: "The object literal notation {} is preferrable.", type: "NewExpression" }] },
{ code: "var foo = new Object(BigInt('1n'))", errors: [{ message: "The object literal notation {} is preferrable.", type: "NewExpression" }] }
]
});

0 comments on commit a5a238b

Please sign in to comment.