Skip to content

Commit

Permalink
feat: handle logical assignment in no-self-assign (#14152)
Browse files Browse the repository at this point in the history
* Fix: handle logical assignment in no-self-assign

* ignore `&=` and `|=`
  • Loading branch information
Zzzen committed Dec 30, 2021
1 parent 3b38018 commit 6802a54
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 1 deletion.
8 changes: 8 additions & 0 deletions docs/rules/no-self-assign.md
Expand Up @@ -24,6 +24,10 @@ foo = foo;
[a, ...b] = [x, ...b];

({a, b} = {a, x});

foo &&= foo;
foo ||= foo;
foo ??= foo;
```
Examples of **correct** code for this rule:
Expand All @@ -50,6 +54,10 @@ obj[a] = obj["a"];
obj.a().b = obj.a().b;
a().b = a().b;

// `&=` and `|=` have an effect on non-integers.
foo &= foo;
foo |= foo;

// Known limitation: this does not support computed properties except single literal or single identifier.
obj[a + b] = obj[a + b];
obj["a" + "b"] = obj["a" + "b"];
Expand Down
2 changes: 1 addition & 1 deletion lib/rules/no-self-assign.js
Expand Up @@ -174,7 +174,7 @@ module.exports = {

return {
AssignmentExpression(node) {
if (node.operator === "=") {
if (["=", "&&=", "||=", "??="].includes(node.operator)) {
eachSelfAssignment(node.left, node.right, props, report);
}
}
Expand Down
19 changes: 19 additions & 0 deletions tests/lib/rules/no-self-assign.js
Expand Up @@ -25,6 +25,8 @@ ruleTester.run("no-self-assign", rule, {
"a += a",
"a = +a",
"a = [a]",
"a &= a",
"a |= a",
{ code: "let a = a", parserOptions: { ecmaVersion: 6 } },
{ code: "const a = a", parserOptions: { ecmaVersion: 6 } },
{ code: "[a] = a", parserOptions: { ecmaVersion: 6 } },
Expand Down Expand Up @@ -167,6 +169,23 @@ ruleTester.run("no-self-assign", rule, {
code: "class C { #field; foo() { [this.#field] = [this.#field]; } }",
parserOptions: { ecmaVersion: 2022 },
errors: [{ messageId: "selfAssignment", data: { name: "this.#field" } }]
},

// logical assignment
{
code: "a &&= a",
parserOptions: { ecmaVersion: 2021 },
errors: [{ messageId: "selfAssignment", data: { name: "a" } }]
},
{
code: "a ||= a",
parserOptions: { ecmaVersion: 2021 },
errors: [{ messageId: "selfAssignment", data: { name: "a" } }]
},
{
code: "a ??= a",
parserOptions: { ecmaVersion: 2021 },
errors: [{ messageId: "selfAssignment", data: { name: "a" } }]
}
]
});

0 comments on commit 6802a54

Please sign in to comment.