UNPKG

1.82 kBJavaScriptView Raw
1/**
2 * Requires sticking unary operators to the right.
3 *
4 * Types: `Array` or `Boolean`
5 *
6 * Values: Array of quoted operators or `true` to disallow space after prefix for all unary operators
7 *
8 * #### Example
9 *
10 * ```js
11 * "disallowSpaceAfterPrefixUnaryOperators": ["++", "--", "+", "-", "~", "!"]
12 * ```
13 *
14 * ##### Valid
15 *
16 * ```js
17 * x = !y; y = ++z;
18 * ```
19 *
20 * ##### Invalid
21 *
22 * ```js
23 * x = ! y; y = ++ z;
24 * ```
25 */
26
27var assert = require('assert');
28var defaultOperators = require('../utils').unaryOperators;
29
30module.exports = function() {};
31
32module.exports.prototype = {
33
34 configure: function(operators) {
35 var isTrue = operators === true;
36
37 assert(
38 Array.isArray(operators) || isTrue,
39 this.getOptionName() + ' option requires array or true value'
40 );
41
42 if (isTrue) {
43 operators = defaultOperators;
44 }
45
46 this._operatorIndex = {};
47 for (var i = 0, l = operators.length; i < l; i++) {
48 this._operatorIndex[operators[i]] = true;
49 }
50 },
51
52 getOptionName: function() {
53 return 'disallowSpaceAfterPrefixUnaryOperators';
54 },
55
56 check: function(file, errors) {
57 var operatorIndex = this._operatorIndex;
58
59 file.iterateNodesByType(['UnaryExpression', 'UpdateExpression'], function(node) {
60 // Check "node.prefix" for prefix type of (inc|dec)rement
61 if (node.prefix && operatorIndex[node.operator]) {
62 var operatorToken = node.getFirstToken();
63 errors.assert.noWhitespaceBetween({
64 token: operatorToken,
65 nextToken: file.getNextToken(operatorToken),
66 message: 'Operator ' + node.operator + ' should stick to operand'
67 });
68 }
69 });
70 }
71};