Skip to content

Commit

Permalink
fix: object-shorthand loses type parameters when auto-fixing (#18438)
Browse files Browse the repository at this point in the history
* fix: object-shorthand loses type parameters when auto-fixing

Fixes #18429

* refactor: remove special astUtils feature

* refactor: judge the first token and use it's index

* style: remove unnecessary condition

* test: update test fixture

* fix: modify the logic to support special test case

* refactor: follow very nice code advice
  • Loading branch information
shulaoda committed May 16, 2024
1 parent b67eba4 commit 39fb0ee
Show file tree
Hide file tree
Showing 3 changed files with 2,177 additions and 20 deletions.
27 changes: 7 additions & 20 deletions lib/rules/object-shorthand.js
Original file line number Diff line number Diff line change
Expand Up @@ -284,35 +284,22 @@ module.exports = {
const arrowToken = sourceCode.getTokenBefore(node.value.body, astUtils.isArrowToken);
const fnBody = sourceCode.text.slice(arrowToken.range[1], node.value.range[1]);

let shouldAddParensAroundParameters = false;
let tokenBeforeParams;

if (node.value.params.length === 0) {
tokenBeforeParams = sourceCode.getFirstToken(node.value, astUtils.isOpeningParenToken);
} else {
tokenBeforeParams = sourceCode.getTokenBefore(node.value.params[0]);
}

if (node.value.params.length === 1) {
const hasParen = astUtils.isOpeningParenToken(tokenBeforeParams);
const isTokenOutsideNode = tokenBeforeParams.range[0] < node.range[0];

shouldAddParensAroundParameters = !hasParen || isTokenOutsideNode;
}
// First token should not be `async`
const firstValueToken = sourceCode.getFirstToken(node.value, {
skip: node.value.async ? 1 : 0
});

const sliceStart = shouldAddParensAroundParameters
? node.value.params[0].range[0]
: tokenBeforeParams.range[0];
const sliceStart = firstValueToken.range[0];
const sliceEnd = sourceCode.getTokenBefore(arrowToken).range[1];
const shouldAddParens = node.value.params.length === 1 && node.value.params[0].range[0] === sliceStart;

const oldParamText = sourceCode.text.slice(sliceStart, sliceEnd);
const newParamText = shouldAddParensAroundParameters ? `(${oldParamText})` : oldParamText;
const newParamText = shouldAddParens ? `(${oldParamText})` : oldParamText;

return fixer.replaceTextRange(
fixRange,
methodPrefix + newParamText + fnBody
);

}

/**
Expand Down

0 comments on commit 39fb0ee

Please sign in to comment.