forked from sveltejs/svelte
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCodeBuilder.js
95 lines (77 loc) · 1.79 KB
/
CodeBuilder.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
const LINE = {};
const BLOCK = {};
export default class CodeBuilder {
constructor ( str = '' ) {
this.result = str;
const initial = str ? ( /\n/.test( str ) ? BLOCK : LINE ) : null;
this.first = initial;
this.last = initial;
this.lastCondition = null;
}
addConditionalLine ( condition, line ) {
if ( condition === this.lastCondition ) {
this.result += `\n\t${line}`;
} else {
if ( this.lastCondition ) {
this.result += `\n}\n\n`;
}
this.result += `if ( ${condition} ) {\n\t${line}`;
this.lastCondition = condition;
}
this.last = BLOCK;
}
addLine ( line ) {
if ( this.lastCondition ) {
this.result += `\n}`;
this.lastCondition = null;
}
if ( this.last === BLOCK ) {
this.result += `\n\n${line}`;
} else if ( this.last === LINE ) {
this.result += `\n${line}`;
} else {
this.result += line;
}
this.last = LINE;
if ( !this.first ) this.first = LINE;
}
addLineAtStart ( line ) {
if ( this.first === BLOCK ) {
this.result = `${line}\n\n${this.result}`;
} else if ( this.first === LINE ) {
this.result = `${line}\n${this.result}`;
} else {
this.result += line;
}
this.first = LINE;
if ( !this.last ) this.last = LINE;
}
addBlock ( block ) {
if ( this.lastCondition ) {
this.result += `\n}`;
this.lastCondition = null;
}
if ( this.result ) {
this.result += `\n\n${block}`;
} else {
this.result += block;
}
this.last = BLOCK;
if ( !this.first ) this.first = BLOCK;
}
addBlockAtStart ( block ) {
if ( this.result ) {
this.result = `${block}\n\n${this.result}`;
} else {
this.result += block;
}
this.first = BLOCK;
if ( !this.last ) this.last = BLOCK;
}
isEmpty () {
return this.result === '';
}
toString () {
return this.result.trim() + ( this.lastCondition ? `\n}` : `` );
}
}