2 * @fileoverview Rule to validate spacing before function paren.
3 * @author Mathias Schreck <https://github.com/lo1tuma>
4 * @copyright 2015 Mathias Schreck
8 //------------------------------------------------------------------------------
10 //------------------------------------------------------------------------------
12 module.exports = function(context) {
14 var configuration = context.options[0],
15 requireAnonymousFunctionSpacing = true,
16 requireNamedFunctionSpacing = true;
18 if (typeof configuration === "object") {
19 requireAnonymousFunctionSpacing = configuration.anonymous !== "never";
20 requireNamedFunctionSpacing = configuration.named !== "never";
21 } else if (configuration === "never") {
22 requireAnonymousFunctionSpacing = false;
23 requireNamedFunctionSpacing = false;
27 * Determines whether two adjacent tokens are have whitespace between them.
28 * @param {Object} left - The left token object.
29 * @param {Object} right - The right token object.
30 * @returns {boolean} Whether or not there is space between the tokens.
32 function isSpaced(left, right) {
33 return left.range[1] < right.range[0];
37 * Determines whether a function has a name.
38 * @param {ASTNode} node The function node.
39 * @returns {boolean} Whether the function has a name.
41 function isNamedFunction(node) {
48 parent = context.getAncestors().pop();
49 return parent.type === "MethodDefinition" ||
50 (parent.type === "Property" &&
52 parent.kind === "get" ||
53 parent.kind === "set" ||
60 * Validates the spacing before function parentheses.
61 * @param {ASTNode} node The node to be validated.
64 function validateSpacingBeforeParentheses(node) {
65 var isNamed = isNamedFunction(node),
71 if (node.generator && !isNamed) {
75 tokens = context.getTokens(node);
79 leftToken = tokens[2];
80 rightToken = tokens[3];
82 // Object methods are named but don't have an id
83 leftToken = context.getTokenBefore(node);
84 rightToken = tokens[0];
88 leftToken = tokens[1];
89 rightToken = tokens[2];
91 // Object methods are named but don't have an id
92 leftToken = context.getTokenBefore(node);
93 rightToken = tokens[0];
96 leftToken = tokens[0];
97 rightToken = tokens[1];
100 location = leftToken.loc.end;
102 if (isSpaced(leftToken, rightToken)) {
103 if ((isNamed && !requireNamedFunctionSpacing) || (!isNamed && !requireAnonymousFunctionSpacing)) {
104 context.report(node, location, "Unexpected space before function parentheses.");
107 if ((isNamed && requireNamedFunctionSpacing) || (!isNamed && requireAnonymousFunctionSpacing)) {
108 context.report(node, location, "Missing space before function parentheses.");
114 "FunctionDeclaration": validateSpacingBeforeParentheses,
115 "FunctionExpression": validateSpacingBeforeParentheses