/
prefer-object-has-own.js
91 lines (78 loc) · 3.08 KB
/
prefer-object-has-own.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
/**
* @fileoverview Prefers Object.hasOwn instead of Object.prototype.hasOwnProperty
* @author Nitin Kumar, Gautam Arora
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const astUtils = require("./utils/ast-utils");
/**
* Checks to see if a property name object exists in the subtree recursively.
* @param {node} node to evalutate.
* @returns {boolean} `true` if object property exists, `false` otherwise.
*/
function checkForObject(node) {
if (!node.object) {
return false;
}
/*
* Object.hasOwnProperty.call(obj, prop) or ({}).hasOwnProperty.call(obj, prop) - `true`
* ({ foo }.hasOwnProperty.call(obj, prop)) - `false`, object literal should be empty
*/
if (node.object.name === "Object" || (node.object.type === "ObjectExpression" && node.object.properties.length === 0)) {
return true;
}
const propertyName = astUtils.getStaticPropertyName(node.object);
if (propertyName === "hasOwnProperty" || propertyName === "prototype") {
return checkForObject(node.object);
}
return false;
}
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../shared/types').Rule} */
module.exports = {
meta: {
type: "suggestion",
docs: {
description:
"disallow use of Object.prototype.hasOwnProperty.call(…) and prefer use of Object.hasOwn(…)",
recommended: false,
url: "https://eslint.org/docs/rules/prefer-object-has-own"
},
schema: [],
messages: {
useHasOwn: "Prefer using Object.hasOwn(…) over Object.prototype.hasOwnProperty.call(…)."
},
fixable: "code"
},
create(context) {
return {
CallExpression(node) {
const calleePropertyName = astUtils.getStaticPropertyName(node.callee);
const objectPropertyName = astUtils.getStaticPropertyName(node.callee.object);
const isObject = checkForObject(node.callee);
// check `Object` scope
const scope = context.getScope();
const variable = astUtils.getVariableByName(scope, "Object");
if (
calleePropertyName === "call" &&
objectPropertyName === "hasOwnProperty" &&
isObject &&
variable.scope.type === "global"
) {
context.report({
node,
messageId: "useHasOwn",
*fix(fixer) {
yield fixer.replaceText(node.callee, "Object.hasOwn");
yield fixer.replaceTextRange([node.arguments[0].range[0], node.arguments[1].range[0]], "");
}
});
}
}
};
}
};