-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfunctionToClass.js
96 lines (88 loc) · 2.44 KB
/
functionToClass.js
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
const estraverse = require('estraverse')
function genClass(id, body) {
return {
type: 'ClassDeclaration',
id,
body: {
type: 'ClassBody',
body
}
}
}
function genConstructor(body) {
return {
type: 'MethodDefinition',
key: {
type: 'Identifier',
name: 'constructor'
},
computed: false,
value: body,
kind: 'constructor',
static: false
}
}
function genMethod(name, body) {
return {
type: 'MethodDefinition',
key: name,
computed: name.type !== 'Identifier',
value: body,
kind: 'method',
static: false
}
}
module.exports = parsed => {
return estraverse.replace(parsed, {
enter: node => {
if (
node.type === 'VariableDeclaration' &&
node.declarations.length === 1
) {
const decl = node.declarations[0]
if (
decl.type === 'VariableDeclarator' &&
decl.init &&
decl.init.type === 'CallExpression' &&
decl.init.callee.type === 'FunctionExpression'
) {
const func = decl.init.callee.body.body
if (
func[0].type === 'FunctionDeclaration' &&
func[func.length - 1].type === 'ReturnStatement'
) {
let rest = func.slice(1, func.length - 1)
if (rest.length === 0) {
return
}
if (
rest[0].type === 'VariableDeclaration' &&
rest[0].declarations &&
rest[0].declarations.length === 1 &&
rest[0].declarations[0].type === 'VariableDeclarator' &&
rest[0].declarations[0].init &&
rest[0].declarations[0].init.type === 'MemberExpression' &&
rest[0].declarations[0].init.property.type === 'Identifier' &&
rest[0].declarations[0].init.property.name === 'prototype'
) {
rest = rest.slice(1)
}
if (rest.every(stmt => (
stmt.type === 'ExpressionStatement' &&
stmt.expression.type === 'AssignmentExpression' &&
stmt.expression.right.type === 'FunctionExpression'
))) {
return genClass(
node.declarations[0].id,
[
genConstructor(func[0]),
...rest.map(stmt => genMethod(stmt.expression.left.property, stmt.expression.right))
]
)
}
}
}
}
}
})
}