1 | /**
|
2 | * @fileoverview Rule to flag trailing commas in object literals.
|
3 | * @author Ian Christian Myers
|
4 | */
|
5 |
|
6 | //------------------------------------------------------------------------------
|
7 | // Rule Definition
|
8 | //------------------------------------------------------------------------------
|
9 |
|
10 | module.exports = function(context) {
|
11 |
|
12 | ;
|
13 |
|
14 | //-------------------------------------------------------------------------
|
15 | // Helpers
|
16 | //-------------------------------------------------------------------------
|
17 |
|
18 | function checkForTrailingComma(node) {
|
19 | var tokens = context.getTokens(node),
|
20 | secondToLastToken = tokens[tokens.length - 2];
|
21 |
|
22 | var items = node.properties || node.elements,
|
23 | lastItem = items[items.length - 1];
|
24 | // The last token in an object/array literal will always be a closing
|
25 | // curly, so we check the second to last token for a comma.
|
26 | if(secondToLastToken.value === "," && items.length && lastItem) {
|
27 | context.report(lastItem, "Trailing comma.");
|
28 | }
|
29 | }
|
30 |
|
31 | //--------------------------------------------------------------------------
|
32 | // Public API
|
33 | //--------------------------------------------------------------------------
|
34 |
|
35 | return {
|
36 | "ObjectExpression": checkForTrailingComma,
|
37 | "ArrayExpression": checkForTrailingComma
|
38 | };
|
39 |
|
40 | };
|