Skip to content

Commit

Permalink
update prefer-arrow-callback
Browse files Browse the repository at this point in the history
  • Loading branch information
mysticatea committed Jun 18, 2020
1 parent 5740538 commit d0fc1b1
Show file tree
Hide file tree
Showing 2 changed files with 101 additions and 28 deletions.
103 changes: 78 additions & 25 deletions lib/rules/prefer-arrow-callback.js
Expand Up @@ -5,6 +5,8 @@

"use strict";

const astUtils = require("./utils/ast-utils");

//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
Expand Down Expand Up @@ -73,23 +75,32 @@ function getCallbackInfo(node) {
// Checks parents recursively.

case "LogicalExpression":
case "ChainExpression":
case "ConditionalExpression":
break;

// Checks whether the parent node is `.bind(this)` call.
case "MemberExpression":
if (parent.object === currentNode &&
if (
parent.object === currentNode &&
!parent.property.computed &&
parent.property.type === "Identifier" &&
parent.property.name === "bind" &&
parent.parent.type === "CallExpression" &&
parent.parent.callee === parent
parent.property.name === "bind"
) {
retv.isLexicalThis = (
parent.parent.arguments.length === 1 &&
parent.parent.arguments[0].type === "ThisExpression"
);
parent = parent.parent;
const memberNode = parent.parent.type === "ChainExpression"
? parent.parent
: parent;

if (
memberNode.parent.type === "CallExpression" &&
memberNode.parent.callee === memberNode
) {
retv.isLexicalThis = (
memberNode.parent.arguments.length === 1 &&
memberNode.parent.arguments[0].type === "ThisExpression"
);
}
parent = memberNode.parent;
} else {
return retv;
}
Expand Down Expand Up @@ -272,7 +283,7 @@ module.exports = {
context.report({
node,
messageId: "preferArrowCallback",
fix(fixer) {
*fix(fixer) {
if ((!callbackInfo.isLexicalThis && scopeInfo.this) || hasDuplicateParams(node.params)) {

/*
Expand All @@ -281,30 +292,72 @@ module.exports = {
* If the callback function has duplicates in its list of parameters (possible in sloppy mode),
* don't replace it with an arrow function, because this is a SyntaxError with arrow functions.
*/
return null;
return; // eslint-disable-line eslint-plugin/fixer-return -- false positive
}

const paramsLeftParen = node.params.length ? sourceCode.getTokenBefore(node.params[0]) : sourceCode.getTokenBefore(node.body, 1);
const paramsRightParen = sourceCode.getTokenBefore(node.body);
const asyncKeyword = node.async ? "async " : "";
const paramsFullText = sourceCode.text.slice(paramsLeftParen.range[0], paramsRightParen.range[1]);
const arrowFunctionText = `${asyncKeyword}${paramsFullText} => ${sourceCode.getText(node.body)}`;
// Remove `.bind(this)` if exists.
if (callbackInfo.isLexicalThis) {
const memberNode = node.parent;
const callNode = memberNode.parent;
const firstTokenToRemove = sourceCode.getTokenAfter(memberNode.object, astUtils.isNotClosingParenToken);
const lastTokenToRemove = sourceCode.getLastToken(callNode);

/*
* If the callback function has `.bind(this)`, replace it with an arrow function and remove the binding.
* Otherwise, just replace the arrow function itself.
*/
const replacedNode = callbackInfo.isLexicalThis ? node.parent.parent : node;
/*
* If the member expression is parenthesized, don't remove the right paren.
* E.g. `(function(){}.bind)(this)`
* ^^^^^^^^^^^^
*/
if (astUtils.isParenthesised(sourceCode, memberNode)) {
return; // eslint-disable-line eslint-plugin/fixer-return -- false positive
}

// If comments exist in the `.bind(this)`, don't remove those.
if (sourceCode.commentsExistBetween(firstTokenToRemove, lastTokenToRemove)) {
return; // eslint-disable-line eslint-plugin/fixer-return -- false positive
}

yield fixer.removeRange([firstTokenToRemove.range[0], lastTokenToRemove.range[1]]);
}

// Convert the function expression to an arrow function.
const functionToken = sourceCode.getFirstToken(node, node.async ? 1 : 0);
const leftParenToken = sourceCode.getTokenAfter(functionToken, astUtils.isOpeningParenToken);

if (sourceCode.commentsExistBetween(functionToken, leftParenToken)) {

// Remove only extra tokens to keep comments.
yield fixer.remove(functionToken);
if (node.id) {
yield fixer.remove(node.id);
}
} else {

// Remove extra tokens and spaces.
yield fixer.removeRange([functionToken.range[0], leftParenToken.range[0]]);
}
yield fixer.insertTextBefore(node.body, "=> ");

// Get the node that will become the new arrow function.
let replacedNode = callbackInfo.isLexicalThis ? node.parent.parent : node;

if (replacedNode.type === "ChainExpression") {
replacedNode = replacedNode.parent;
}

/*
* If the replaced node is part of a BinaryExpression, LogicalExpression, or MemberExpression, then
* the arrow function needs to be parenthesized, because `foo || () => {}` is invalid syntax even
* though `foo || function() {}` is valid.
*/
const needsParens = replacedNode.parent.type !== "CallExpression" && replacedNode.parent.type !== "ConditionalExpression";
const replacementText = needsParens ? `(${arrowFunctionText})` : arrowFunctionText;

return fixer.replaceText(replacedNode, replacementText);
if (
replacedNode.parent.type !== "CallExpression" &&
replacedNode.parent.type !== "ConditionalExpression" &&
!astUtils.isParenthesised(sourceCode, replacedNode) &&
!astUtils.isParenthesised(sourceCode, node)
) {
yield fixer.insertTextBefore(replacedNode, "(");
yield fixer.insertTextAfter(replacedNode, ")");
}
}
});
}
Expand Down
26 changes: 23 additions & 3 deletions tests/lib/rules/prefer-arrow-callback.js
Expand Up @@ -21,7 +21,7 @@ const errors = [{
type: "FunctionExpression"
}];

const ruleTester = new RuleTester({ parserOptions: { ecmaVersion: 6 } });
const ruleTester = new RuleTester({ parserOptions: { ecmaVersion: 2020 } });

ruleTester.run("prefer-arrow-callback", rule, {
valid: [
Expand Down Expand Up @@ -165,13 +165,33 @@ ruleTester.run("prefer-arrow-callback", rule, {
{
code: "qux(async function (foo = 1, bar = 2, baz = 3) { return baz; })",
output: "qux(async (foo = 1, bar = 2, baz = 3) => { return baz; })",
parserOptions: { ecmaVersion: 8 },
errors
},
{
code: "qux(async function (foo = 1, bar = 2, baz = 3) { return this; }.bind(this))",
output: "qux(async (foo = 1, bar = 2, baz = 3) => { return this; })",
parserOptions: { ecmaVersion: 8 },
errors
},

// Optional chaining
{
code: "foo?.(function() {});",
output: "foo?.(() => {});",
errors
},
{
code: "foo?.(function() { return this; }.bind(this));",
output: "foo?.(() => { return this; });",
errors
},
{
code: "foo(function() { return this; }?.bind(this));",
output: "foo(() => { return this; });",
errors
},
{
code: "foo((function() { return this; }?.bind)(this));",
output: null,
errors
}
]
Expand Down

0 comments on commit d0fc1b1

Please sign in to comment.