Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: handle logical assignment in no-self-assign #14152

Merged
merged 3 commits into from Dec 30, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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" } }]
}
]
});