Skip to content

Commit bc51eee

Browse files
authored
fix: prefer-arrow-callback false positive in conditional test (#21373)
- A function in the test of a conditional can never be the conditional's value, so it is not a callback of the enclosing call. The rule reported it, and the autofix produced invalid code (`foo(() => {} ? a : b)`). - Functions in the consequent or the alternate are still reported and fixed.
1 parent bbff86c commit bc51eee

2 files changed

Lines changed: 19 additions & 0 deletions

File tree

‎lib/rules/prefer-arrow-callback.js‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,13 @@ function getCallbackInfo(node) {
8383

8484
case "LogicalExpression":
8585
case "ChainExpression":
86+
break;
87+
88+
// The test of a conditional is never its value.
8689
case "ConditionalExpression":
90+
if (parent.test === currentNode) {
91+
return retv;
92+
}
8793
break;
8894

8995
// Checks whether the parent node is `.bind(this)` call.

‎tests/lib/rules/prefer-arrow-callback.js‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,14 @@ ruleTester.run("prefer-arrow-callback", rule, {
4949
"foo(function bar() { this; }.bind(this, somethingElse));",
5050
"foo((function() {}).bind.bar)",
5151
"foo((function() { this.bar(); }).bind(obj).bind(this))",
52+
"foo(function() {} ? a : b);",
53+
"foo((function() {}) ? a : b);",
54+
"foo(function() { this; }.bind(this) ? a : b);",
55+
"foo(function() { this; }?.bind(this) ? a : b);",
56+
"foo(bar ? function() {} ? a : b : c);",
57+
"foo(function() {} || a ? b : c);",
58+
"new Foo(function() {} ? a : b);",
59+
"foo(async function() {} ? a : b);",
5260
],
5361
invalid: [
5462
{
@@ -83,6 +91,11 @@ ruleTester.run("prefer-arrow-callback", rule, {
8391
output: "foo(bar ? () => {} : () => {});",
8492
errors: [errors[0], errors[0]],
8593
},
94+
{
95+
code: "foo(function() {} ? function() {} : b);",
96+
output: "foo(function() {} ? () => {} : b);",
97+
errors,
98+
},
8699
{
87100
code: "foo(function() { (function() { this; }); });",
88101
output: "foo(() => { (function() { this; }); });",

0 commit comments

Comments
 (0)