-
Notifications
You must be signed in to change notification settings - Fork 3
/
implicit-return-to-explicit.ts
59 lines (48 loc) · 1.28 KB
/
implicit-return-to-explicit.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import {Fixer} from '../types'
import * as jscodeshift from 'jscodeshift'
import * as Range from '../range'
import * as Position from '../pos'
import * as Ast from '../ast'
import * as Patch from '../patch'
type Data = Position.t
const fixer: Fixer<Data> = {
suggestCodeAction(params) {
const {j, ast} = params
const collection = ast.find(
j.ArrowFunctionExpression,
(n: jscodeshift.ArrowFunctionExpression) => {
return n.loc && Range.isInside(params.selection, n.loc) && j.Expression.check(n.body)
}
)
if (collection.size() !== 1) {
return null
}
const node = collection.nodes()[0]
if (!node.loc) {
return null
}
return {
title: `Use explicit return`,
data: node.loc.start,
}
},
createEdit(params) {
const {data, ast, j} = params
const node = Ast.findFirstNode(ast, j.ArrowFunctionExpression, n => Ast.isOnPosition(n, data))
if (!node) {
return null
}
const body = node.body
if (j.BlockStatement.check(body)) {
return null
}
const newNode = j.arrowFunctionExpression(
node.params,
j.blockStatement([j.returnStatement(body)]),
false
)
newNode.async = node.async
return Patch.replaceNode(j, node, newNode)
},
}
export default fixer