UNPKG

2.5 kBJavaScriptView Raw
1/**
2 * @fileoverview Rule to flag trailing underscores in variable declarations.
3 * @author Matt DuVall <http://www.mattduvall.com>
4 */
5
6//------------------------------------------------------------------------------
7// Rule Definition
8//------------------------------------------------------------------------------
9
10module.exports = function(context) {
11
12 "use strict";
13
14 //-------------------------------------------------------------------------
15 // Helpers
16 //-------------------------------------------------------------------------
17
18 function hasTrailingUnderscore(identifier) {
19 var len = identifier.length;
20
21 return identifier !== "_" && (identifier[0] === "_" || identifier[len - 1] === "_");
22 }
23
24 function isSpecialCaseIdentifierForMemberExpression(identifier) {
25 return identifier === "__proto__";
26 }
27
28 function isSpecialCaseIdentifierInVariableExpression(identifier) {
29 // Checks for the underscore library usage here
30 return identifier === "_";
31 }
32
33 function checkForTrailingUnderscoreInFunctionDeclaration(node) {
34 var identifier = node.id.name;
35
36 if (typeof identifier !== "undefined" && hasTrailingUnderscore(identifier)) {
37 context.report(node, "Unexpected dangling '_' in '" + identifier + "'.");
38 }
39 }
40
41 function checkForTrailingUnderscoreInVariableExpression(node) {
42 var identifier = node.id.name;
43
44 if (typeof identifier !== "undefined" && hasTrailingUnderscore(identifier) &&
45 !isSpecialCaseIdentifierInVariableExpression(identifier)) {
46 context.report(node, "Unexpected dangling '_' in '" + identifier + "'.");
47 }
48 }
49
50 function checkForTrailingUnderscoreInMemberExpression(node) {
51 var identifier = node.property.name;
52
53 if (typeof identifier !== "undefined" && hasTrailingUnderscore(identifier) &&
54 !isSpecialCaseIdentifierForMemberExpression(identifier)) {
55 context.report(node, "Unexpected dangling '_' in '" + identifier + "'.");
56 }
57 }
58
59 //--------------------------------------------------------------------------
60 // Public API
61 //--------------------------------------------------------------------------
62
63 return {
64 "FunctionDeclaration": checkForTrailingUnderscoreInFunctionDeclaration,
65 "VariableDeclarator": checkForTrailingUnderscoreInVariableExpression,
66 "MemberExpression": checkForTrailingUnderscoreInMemberExpression
67 };
68
69};