1/** 2 * @fileoverview Align multiline variable assignments 3 * @author Rich Trott 4 */ 5'use strict'; 6 7//------------------------------------------------------------------------------ 8// Rule Definition 9//------------------------------------------------------------------------------ 10function getBinaryExpressionStarts(binaryExpression, starts) { 11 function getStartsFromOneSide(side, starts) { 12 starts.push(side.loc.start); 13 if (side.type === 'BinaryExpression') { 14 starts = getBinaryExpressionStarts(side, starts); 15 } 16 return starts; 17 } 18 19 starts = getStartsFromOneSide(binaryExpression.left, starts); 20 starts = getStartsFromOneSide(binaryExpression.right, starts); 21 return starts; 22} 23 24function checkExpressionAlignment(expression) { 25 if (!expression) 26 return; 27 28 var msg = ''; 29 30 switch (expression.type) { 31 case 'BinaryExpression': 32 var starts = getBinaryExpressionStarts(expression, []); 33 var startLine = starts[0].line; 34 const startColumn = starts[0].column; 35 starts.forEach((loc) => { 36 if (loc.line > startLine) { 37 startLine = loc.line; 38 if (loc.column !== startColumn) { 39 msg = 'Misaligned multiline assignment'; 40 } 41 } 42 }); 43 break; 44 } 45 return msg; 46} 47 48function testAssignment(context, node) { 49 const msg = checkExpressionAlignment(node.right); 50 if (msg) 51 context.report(node, msg); 52} 53 54function testDeclaration(context, node) { 55 node.declarations.forEach((declaration) => { 56 const msg = checkExpressionAlignment(declaration.init); 57 // const start = declaration.init.loc.start; 58 if (msg) 59 context.report(node, msg); 60 }); 61} 62 63module.exports = function(context) { 64 return { 65 'AssignmentExpression': (node) => testAssignment(context, node), 66 'VariableDeclaration': (node) => testDeclaration(context, node) 67 }; 68}; 69