2 * @fileoverview Rule to forbid or enforce dangling commas.
3 * @author Ian Christian Myers
4 * @copyright 2015 Mathias Schreck
5 * @copyright 2013 Ian Christian Myers
10 //------------------------------------------------------------------------------
12 //------------------------------------------------------------------------------
14 module.exports = function (context) {
15 var allowDangle = context.options[0];
16 var forbidDangle = allowDangle !== "always-multiline" && allowDangle !== "always";
17 var UNEXPECTED_MESSAGE = "Unexpected trailing comma.";
18 var MISSING_MESSAGE = "Missing trailing comma.";
21 * Checks the given node for trailing comma and reports violations.
22 * @param {ASTNode} node The node of an ObjectExpression or ArrayExpression
25 function checkForTrailingComma(node) {
26 var items = node.properties || node.elements,
27 length = items.length,
28 nodeIsMultiLine = node.loc.start.line !== node.loc.end.line,
34 lastItem = items[length - 1];
36 penultimateToken = context.getLastToken(node, 1);
37 hasDanglingComma = penultimateToken.value === ",";
39 if (forbidDangle && hasDanglingComma) {
40 context.report(lastItem, penultimateToken.loc.start, UNEXPECTED_MESSAGE);
41 } else if (allowDangle === "always-multiline") {
42 if (hasDanglingComma && !nodeIsMultiLine) {
43 context.report(lastItem, penultimateToken.loc.start, UNEXPECTED_MESSAGE);
44 } else if (!hasDanglingComma && nodeIsMultiLine) {
45 context.report(lastItem, penultimateToken.loc.end, MISSING_MESSAGE);
47 } else if (allowDangle === "always" && !hasDanglingComma) {
48 context.report(lastItem, lastItem.loc.end, MISSING_MESSAGE);
55 "ObjectExpression": checkForTrailingComma,
56 "ArrayExpression": checkForTrailingComma