2 * @fileoverview Rule to replace assignment expressions with operator assignment
3 * @author Brandon Mills
4 * @copyright 2014 Brandon Mills. All rights reserved.
8 //------------------------------------------------------------------------------
10 //------------------------------------------------------------------------------
13 * Checks whether an operator is commutative and has an operator assignment
15 * @param {string} operator Operator to check.
16 * @returns {boolean} True if the operator is commutative and has a
19 function isCommutativeOperatorWithShorthand(operator) {
20 return ["*", "&", "^", "|"].indexOf(operator) >= 0;
24 * Checks whether an operator is not commuatative and has an operator assignment
26 * @param {string} operator Operator to check.
27 * @returns {boolean} True if the operator is not commuatative and has
30 function isNonCommutativeOperatorWithShorthand(operator) {
31 return ["+", "-", "/", "%", "<<", ">>", ">>>"].indexOf(operator) >= 0;
34 //------------------------------------------------------------------------------
36 //------------------------------------------------------------------------------
39 * Checks whether two expressions reference the same value. For example:
44 * @param {ASTNode} a Left side of the comparison.
45 * @param {ASTNode} b Right side of the comparison.
46 * @returns {boolean} True if both sides match and reference the same value.
49 if (a.type !== b.type) {
55 return a.name === b.name;
57 return a.value === b.value;
58 case "MemberExpression":
62 return same(a.object, b.object) && same(a.property, b.property);
68 module.exports = function(context) {
71 * Ensures that an assignment uses the shorthand form where possible.
72 * @param {ASTNode} node An AssignmentExpression node.
75 function verify(node) {
76 var expr, left, operator;
78 if (node.operator !== "=" || node.right.type !== "BinaryExpression") {
84 operator = expr.operator;
86 if (isCommutativeOperatorWithShorthand(operator)) {
87 if (same(left, expr.left) || same(left, expr.right)) {
88 context.report(node, "Assignment can be replaced with operator assignment.");
90 } else if (isNonCommutativeOperatorWithShorthand(operator)) {
91 if (same(left, expr.left)) {
92 context.report(node, "Assignment can be replaced with operator assignment.");
98 * Warns if an assignment expression uses operator assignment shorthand.
99 * @param {ASTNode} node An AssignmentExpression node.
102 function prohibit(node) {
103 if (node.operator !== "=") {
104 context.report(node, "Unexpected operator assignment shorthand.");
109 "AssignmentExpression": context.options[0] !== "never" ? verify : prohibit