Skip to content
Permalink
Browse files

Update: optionally allow bitwise operators (fixes #4742)

  • Loading branch information...
Swaagie committed Dec 22, 2015
1 parent 557a0e1 commit 4931f56e9901d8efc3d4e084122af52fd2730507
Showing with 49 additions and 10 deletions.
  1. +8 −0 docs/rules/no-bitwise.md
  2. +37 −9 lib/rules/no-bitwise.js
  3. +4 −1 tests/lib/rules/no-bitwise.js
@@ -57,3 +57,11 @@ var x = y < z;
x += y;
```

This rule takes one argument, an object with the `allow` property. This allows the listed bitwise operators to be used as exceptions to the rule. For example:

```js
/*eslint no-bitwise: [2, { allow: ["~"] }] */
~[1,2,3].indexOf(1) === -1;
```
@@ -5,17 +5,22 @@

"use strict";

//
// Set of bitwise operators.
//
var BITWISE_OPERATORS = [
"^", "|", "&", "<<", ">>", ">>>",
"^=", "|=", "&=", "<<=", ">>=", ">>>=",
"~"
];

//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------

module.exports = function(context) {

var BITWISE_OPERATORS = [
"^", "|", "&", "<<", ">>", ">>>",
"^=", "|=", "&=", "<<=", ">>=", ">>>=",
"~"
];
var options = context.options[0] || {};
var allowed = options.allow || [];

/**
* Reports an unexpected use of a bitwise operator.
@@ -35,13 +40,22 @@ module.exports = function(context) {
return BITWISE_OPERATORS.indexOf(node.operator) !== -1;
}

/**
* Checks if exceptions were provided, e.g. `{ allow: ['~', '|'] }`.
* @param {ASTNode} node The node to check.
* @returns {boolean} Whether or not the node has a bitwise operator.
*/
function allowedOperator(node) {
return allowed.indexOf(node.operator) !== -1;
}

/**
* Report if the given node contains a bitwise operator.
* @param {ASTNode} node The node to check.
* @param {ASTNode} node The node to check.
* @returns {void}
*/
function checkNodeForBitwiseOperator(node) {
if (hasBitwiseOperator(node)) {
if (hasBitwiseOperator(node) && !allowedOperator(node)) {
report(node);
}
}
@@ -54,4 +68,18 @@ module.exports = function(context) {

};

module.exports.schema = [];
module.exports.schema = [
{
"type": "object",
"properties": {
"allow": {
"type": "array",
"items": {
"enum": BITWISE_OPERATORS
},
"uniqueItems": true
}
},
"additionalProperties": false
}
];
@@ -21,7 +21,10 @@ ruleTester.run("no-bitwise", rule, {
valid: [
"a + b",
"!a",
"a += b"
"a += b",
{ code: "~[1, 2, 3].indexOf(1)", options: [{ allow: ["~"] }]},
{ code: "~1<<2 === -8", options: [{ allow: ["~", "<<"] }]},
{ code: "~1<<2 === -8", options: [{ allow: ["~", "<<"] }]}
],
invalid: [
{ code: "a ^ b", errors: [{ message: "Unexpected use of '^'.", type: "BinaryExpression"}] },

0 comments on commit 4931f56

Please sign in to comment.
You can’t perform that action at this time.