2 * @fileoverview Rule to ensure newline per method call when chaining calls
3 * @author Rajendra Patil
4 * @author Burak Yigit Kaya
9 const astUtils = require("./utils/ast-utils");
11 //------------------------------------------------------------------------------
13 //------------------------------------------------------------------------------
20 description: "require a newline after each call in a method chain",
21 category: "Stylistic Issues",
23 url: "https://eslint.org/docs/rules/newline-per-chained-call"
26 fixable: "whitespace",
31 ignoreChainWithDepth: {
38 additionalProperties: false
41 expected: "Expected line break before `{{callee}}`."
47 const options = context.options[0] || {},
48 ignoreChainWithDepth = options.ignoreChainWithDepth || 2;
50 const sourceCode = context.getSourceCode();
53 * Get the prefix of a given MemberExpression node.
54 * If the MemberExpression node is a computed value it returns a
55 * left bracket. If not it returns a period.
56 * @param {ASTNode} node A MemberExpression node to get
57 * @returns {string} The prefix of the node.
59 function getPrefix(node) {
60 return node.computed ? "[" : ".";
64 * Gets the property text of a given MemberExpression node.
65 * If the text is multiline, this returns only the first line.
66 * @param {ASTNode} node A MemberExpression node to get.
67 * @returns {string} The property text of the node.
69 function getPropertyText(node) {
70 const prefix = getPrefix(node);
71 const lines = sourceCode.getText(node.property).split(astUtils.LINEBREAK_MATCHER);
72 const suffix = node.computed && lines.length === 1 ? "]" : "";
74 return prefix + lines[0] + suffix;
78 "CallExpression:exit"(node) {
79 if (!node.callee || node.callee.type !== "MemberExpression") {
83 const callee = node.callee;
84 let parent = callee.object;
87 while (parent && parent.callee) {
89 parent = parent.callee.object;
92 if (depth > ignoreChainWithDepth && astUtils.isTokenOnSameLine(callee.object, callee.property)) {
94 node: callee.property,
95 loc: callee.property.loc.start,
96 messageId: "expected",
98 callee: getPropertyText(callee)
101 const firstTokenAfterObject = sourceCode.getTokenAfter(callee.object, astUtils.isNotClosingParenToken);
103 return fixer.insertTextBefore(firstTokenAfterObject, "\n");