-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
55 lines (50 loc) · 1.56 KB
/
index.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
'use strict';
var tk = require('rocambole-token');
var wrapWithBraces = function (node, prop) {
var oldNode = node[prop];
var finalToken = oldNode.endToken;
//apply a custom fix if endtoken is empty
if (tk.isEmpty(oldNode.endToken)) {
finalToken = tk.findPrevNonEmpty(oldNode.endToken);
}
var newNode = {
type: 'BlockStatement',
parent: oldNode.parent,
root: oldNode.root,
body: [oldNode],
startToken: tk.before(oldNode.startToken, {
type: 'Punctuator',
value: '{'
}),
endToken: tk.after(finalToken, {
type: 'Punctuator',
value: '}'
})
};
oldNode.parent = newNode;
node[prop] = newNode;
};
var checkConditionals = function (node) {
//replace regular conditionals
if (node.consequent.type !== 'BlockStatement') {
wrapWithBraces(node, 'consequent');
}
//replace else alternate conditional
if (node.alternate && node.alternate.type !== 'IfStatement' && node.alternate.type !== 'BlockStatement') {
wrapWithBraces(node, 'alternate');
}
};
var isLoopNode = function (node) {
return node.type === 'WhileStatement' ||
node.type === 'DoWhileStatement' ||
node.type === 'ForStatement' ||
node.type === 'ForInStatement';
};
exports.nodeBefore = function (node) {
//handle conditionals
if (node.type === 'IfStatement') {
checkConditionals(node);
} else if (isLoopNode(node) && node.body.type !== 'BlockStatement') {
wrapWithBraces(node, 'body');
}
};