forked from ChromeDevTools/devtools-frontend
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathno-underscored-properties.js
67 lines (61 loc) · 1.99 KB
/
no-underscored-properties.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
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
'use strict';
function hasPublicMethodForUnderscoredProperty(node) {
const nodeName = node.key.name;
// We allow a property to start with an underscore if the class defines a public getter without an underscore.
const methodsDeclared =
node.parent.body.filter(item => item.type === 'MethodDefinition' && item.key.type === 'Identifier');
const hasMethodDeclaredWithNonUnderscoredName = methodsDeclared.find(method => {
const methodName = method.key.name;
return (nodeName.slice(1) === methodName);
});
return hasMethodDeclaredWithNonUnderscoredName;
}
function checkNodeForUnderscoredProperties(context, node, typeOfNode) {
if (node.key.type !== 'Identifier') {
return;
}
const nodeName = node.key.name;
if (!nodeName.startsWith('_')) {
return;
}
// We allow a property to start with an underscore if the class defines a public getter without an underscore.
if (hasPublicMethodForUnderscoredProperty(node)) {
return;
}
context.report({
node,
data: {propName: nodeName, typeOfNode},
message: 'Class {{typeOfNode}} {{propName}} should not begin with an underscore.'
});
}
/**
* @type {import('eslint').Rule.RuleModule}
*/
module.exports = {
meta: {
type: 'problem',
docs: {
description: 'enforce that class properties and methods do not start with an underscore',
category: 'Possible Errors',
},
fixable: 'code',
schema: [] // no options
},
create: function(context) {
return {
PropertyDefinition(node) {
checkNodeForUnderscoredProperties(context, node, 'property');
},
MethodDefinition(node) {
if (node.parent.type !== 'ClassBody') {
// We only want to check method declarations within classes.
return;
}
checkNodeForUnderscoredProperties(context, node, 'method');
}
};
}
};