forked from sindresorhus/eslint-plugin-unicorn
/
prefer-object-has-own.js
105 lines (96 loc) · 2.34 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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
'use strict';
const {isNodeMatches, isNodeMatchesNameOrPath} = require('./utils/is-node-matches.js');
const {
objectPrototypeMethodSelector,
methodCallSelector,
callExpressionSelector,
} = require('./selectors/index.js');
const {fixSpaceAroundKeyword} = require('./fix/index.js');
const MESSAGE_ID = 'prefer-object-has-own';
const messages = {
[MESSAGE_ID]: 'Use `Object.hasOwn(…)` instead of `{{description}}(…)`.',
};
const objectPrototypeHasOwnProperty = [
methodCallSelector({method: 'call', argumentsLength: 2}),
' > ',
objectPrototypeMethodSelector({
path: 'object',
method: 'hasOwnProperty',
}),
'.callee',
].join('');
const lodashHasFunctions = [
'_.has',
'lodash.has',
'underscore.has',
];
/** @param {import('eslint').Rule.RuleContext} context */
const create = context => {
const {functions: configFunctions} = {
functions: [],
...context.options[0],
};
const functions = [...configFunctions, ...lodashHasFunctions];
return Object.fromEntries(
[
{
selector: objectPrototypeHasOwnProperty,
description: 'Object.prototype.hasOwnProperty.call',
},
{
selector: `${callExpressionSelector({argumentsLength: 2})} > .callee`,
test: node => isNodeMatches(node, functions),
description: node => functions.find(nameOrPath => isNodeMatchesNameOrPath(node, nameOrPath)).trim(),
},
].map(({selector, test, description}) => [
selector,
node => {
if (test && !test(node)) {
return;
}
return {
node,
messageId: MESSAGE_ID,
data: {
description: typeof description === 'string' ? description : description(node),
},
/** @param {import('eslint').Rule.RuleFixer} fixer */
* fix(fixer) {
yield fixer.replaceText(node, 'Object.hasOwn');
if (
node.object
&& node.object.object
&& node.object.object.type === 'ObjectExpression'
) {
yield * fixSpaceAroundKeyword(fixer, node.parent, context.getSourceCode());
}
},
};
},
]),
);
};
const schema = [
{
type: 'object',
additionalProperties: false,
properties: {
functions: {
type: 'array',
uniqueItems: true,
},
},
},
];
module.exports = {
create,
meta: {
type: 'suggestion',
docs: {
description: 'Prefer `Object.hasOwn(…)` over `Object.prototype.hasOwnProperty.call(…)`.',
},
fixable: 'code',
schema,
messages,
},
};