UNPKG

1.68 kBJavaScriptView Raw
1/**
2 * Requires the variable to be the left hand operator when doing a boolean comparison
3 *
4 * Type: `Array` or `Boolean`
5 *
6 * Values: Array of quoted operators or `true` to disallow yoda conditions for most possible comparison operators
7 *
8 * #### Example
9 *
10 * ```js
11 * "disallowYodaConditions": [
12 * "==",
13 * "===",
14 * "!=",
15 * "!=="
16 * ]
17 * ```
18 *
19 * ##### Valid
20 *
21 * ```js
22 * if (a == 1) {
23 * return
24 * }
25 * ```
26 *
27 * ##### Invalid
28 *
29 * ```js
30 * if (1 == a) {
31 * return
32 * }
33 * ```
34 */
35
36var assert = require('assert');
37
38module.exports = function() {};
39
40module.exports.prototype = {
41
42 configure: function(operators) {
43 var isTrue = operators === true;
44
45 assert(
46 Array.isArray(operators) || isTrue,
47 this.getOptionName() + ' option requires array or true value'
48 );
49
50 if (isTrue) {
51 operators = ['==', '===', '!=', '!=='];
52 }
53
54 this._operatorIndex = {};
55 for (var i = 0, l = operators.length; i < l; i++) {
56 this._operatorIndex[operators[i]] = true;
57 }
58 },
59
60 getOptionName: function() {
61 return 'disallowYodaConditions';
62 },
63
64 check: function(file, errors) {
65 var operators = this._operatorIndex;
66 file.iterateNodesByType('BinaryExpression', function(node) {
67 if (operators[node.operator]) {
68 if (
69 node.left.type.indexOf('Literal') > -1 ||
70 (node.left.type === 'Identifier' && node.left.name === 'undefined')
71 ) {
72 errors.add('Yoda condition', node.left);
73 }
74 }
75 });
76 }
77
78};