Skip to content

Commit

Permalink
fix(inline-arrow): add parens for object expression
Browse files Browse the repository at this point in the history
  • Loading branch information
sxzz committed May 13, 2024
1 parent fdf56e1 commit db747d2
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 2 deletions.
10 changes: 10 additions & 0 deletions src/commands/_utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,13 @@ export function insideRange(node: Tree.Node, range: [number, number], includeSta
&& (includeEnd ? node.range[1] <= range[1] : node.range[1] < range[1])
)
}

export function unwrapType(node: Tree.Node) {
if (node.type === 'TSAsExpression' // foo as number
|| node.type === 'TSSatisfiesExpression' // foo satisfies T
|| node.type === 'TSNonNullExpression' // foo!
|| node.type === 'TSInstantiationExpression' // foo<string>
|| node.type === 'TSTypeAssertion') // <number>foo
return node.expression
return node
}
12 changes: 12 additions & 0 deletions src/commands/inline-arrow.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,4 +56,16 @@ run(
`,
errors: ['command-fix'],
},
{
code: $`
/// inline-arrow
export const foo = () => {
return { a: 'b' } as any
}
`,
output: $`
export const foo = () => ({ a: 'b' } as any)
`,
errors: ['command-fix'],
},
)
10 changes: 8 additions & 2 deletions src/commands/inline-arrow.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { Command, Tree } from '../types'
import { unwrapType } from './_utils'

export const inlineArrow: Command = {
name: 'inline-arrow',
Expand All @@ -18,15 +19,20 @@ export const inlineArrow: Command = {
)
return ctx.reportError('Arrow function body must have a single statement')
const statement = statements[0] as Tree.ReturnStatement | undefined
const argument: Tree.Node | null = statement?.argument ? unwrapType(statement.argument) : null
const isObject = (argument?.type === 'ObjectExpression')

ctx.report({
node: arrowFn,
loc: body.loc,
message: 'Inline arrow function',
fix(fixer) {
return fixer.replaceTextRange(body.range, statement && statement.argument
let raw = statement && statement.argument
? ctx.getTextOf(statement.argument)
: 'undefined')
: 'undefined'
if (isObject)
raw = `(${raw})`
return fixer.replaceTextRange(body.range, raw)
},
})
},
Expand Down

0 comments on commit db747d2

Please sign in to comment.