Yang Guo | 4fd355c | 2019-09-19 10:59:03 +0200 | [diff] [blame] | 1 | /** |
| 2 | * @fileoverview A rule to disallow calls to the Object constructor |
| 3 | * @author Matt DuVall <http://www.mattduvall.com/> |
| 4 | */ |
| 5 | |
| 6 | "use strict"; |
| 7 | |
| 8 | //------------------------------------------------------------------------------ |
Tim van der Lippe | 16aca39 | 2020-11-13 11:37:13 +0000 | [diff] [blame] | 9 | // Requirements |
| 10 | //------------------------------------------------------------------------------ |
| 11 | |
| 12 | const astUtils = require("./utils/ast-utils"); |
| 13 | |
| 14 | //------------------------------------------------------------------------------ |
Yang Guo | 4fd355c | 2019-09-19 10:59:03 +0200 | [diff] [blame] | 15 | // Rule Definition |
| 16 | //------------------------------------------------------------------------------ |
| 17 | |
Tim van der Lippe | 0ceb465 | 2022-01-06 14:23:36 +0100 | [diff] [blame^] | 18 | /** @type {import('../shared/types').Rule} */ |
Yang Guo | 4fd355c | 2019-09-19 10:59:03 +0200 | [diff] [blame] | 19 | module.exports = { |
| 20 | meta: { |
| 21 | type: "suggestion", |
| 22 | |
| 23 | docs: { |
| 24 | description: "disallow `Object` constructors", |
Yang Guo | 4fd355c | 2019-09-19 10:59:03 +0200 | [diff] [blame] | 25 | recommended: false, |
| 26 | url: "https://eslint.org/docs/rules/no-new-object" |
| 27 | }, |
| 28 | |
Tim van der Lippe | 16aca39 | 2020-11-13 11:37:13 +0000 | [diff] [blame] | 29 | schema: [], |
| 30 | |
| 31 | messages: { |
| 32 | preferLiteral: "The object literal notation {} is preferrable." |
| 33 | } |
Yang Guo | 4fd355c | 2019-09-19 10:59:03 +0200 | [diff] [blame] | 34 | }, |
| 35 | |
| 36 | create(context) { |
Yang Guo | 4fd355c | 2019-09-19 10:59:03 +0200 | [diff] [blame] | 37 | return { |
Yang Guo | 4fd355c | 2019-09-19 10:59:03 +0200 | [diff] [blame] | 38 | NewExpression(node) { |
Tim van der Lippe | 16aca39 | 2020-11-13 11:37:13 +0000 | [diff] [blame] | 39 | const variable = astUtils.getVariableByName( |
| 40 | context.getScope(), |
| 41 | node.callee.name |
| 42 | ); |
| 43 | |
| 44 | if (variable && variable.identifiers.length > 0) { |
| 45 | return; |
| 46 | } |
| 47 | |
Yang Guo | 4fd355c | 2019-09-19 10:59:03 +0200 | [diff] [blame] | 48 | if (node.callee.name === "Object") { |
Tim van der Lippe | 16aca39 | 2020-11-13 11:37:13 +0000 | [diff] [blame] | 49 | context.report({ |
| 50 | node, |
| 51 | messageId: "preferLiteral" |
| 52 | }); |
Yang Guo | 4fd355c | 2019-09-19 10:59:03 +0200 | [diff] [blame] | 53 | } |
| 54 | } |
| 55 | }; |
Yang Guo | 4fd355c | 2019-09-19 10:59:03 +0200 | [diff] [blame] | 56 | } |
| 57 | }; |