UNPKG

2.2 kBJavaScriptView Raw
1/**
2 * Disallows sticking unary operators to the right.
3 *
4 * Types: `Array` or `Boolean`
5 *
6 * Values: Array of quoted operators or `true` to require space after prefix for all unary operators
7 *
8 * #### Example
9 *
10 * ```js
11 * "requireSpaceAfterPrefixUnaryOperators": ["++", "--", "+", "-", "~", "!"]
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 'requireSpaceAfterPrefixUnaryOperators';
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 argument = node.argument.type;
63 var operatorToken = node.getFirstToken();
64 var nextToken = file.getNextToken(operatorToken);
65
66 // Do not report consecutive operators (#405)
67 if (
68 argument === 'UnaryExpression' || argument === 'UpdateExpression' &&
69 nextToken.value !== '('
70 ) {
71 return;
72 }
73
74 errors.assert.whitespaceBetween({
75 token: operatorToken,
76 nextToken: nextToken,
77 message: 'Operator ' + node.operator + ' should not stick to operand'
78 });
79 }
80 });
81 }
82};