-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreplaceVariableDeclaration.js
More file actions
56 lines (51 loc) · 1.29 KB
/
replaceVariableDeclaration.js
File metadata and controls
56 lines (51 loc) · 1.29 KB
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
function assignmentNode(declarationNode, globalName) {
var identifier = declarationNode.id;
var valueNode = declarationNode.init;
return {
"type": "AssignmentExpression",
"operator": "=",
"left": {
"type": "MemberExpression",
"object": {
"type": "Identifier",
"name": "window"
},
"property": {
"type": "Identifier",
"name": identifier.name
},
"computed": false
},
"right": valueNode
};
}
function assignmentsNode(declarationsNodes, globalName) {
return {
"type": "ExpressionStatement",
"expression": {
"type": "SequenceExpression",
"expressions": declarationsNodes.map(assignmentNode, globalName)
}
};
}
function replace(replaceFn, ast, test, globalName) {
globalName = globalName || 'window';
var replacement = {
'VariableDeclaration': {
replace: function (node) {
var declarations = node.declarations;
if (declarations.length === 1) {
return {
"type": "ExpressionStatement",
"expression": assignmentNode(declarations[0], globalName)
};
} else {
return assignmentsNode(declarations, globalName);
}
},
test: test
}
};
replaceFn(ast, replacement);
}
module.exports = replace;