/
code.ts
49 lines (44 loc) · 1.55 KB
/
code.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
import { lines } from './util';
export type CodeLine = { code: string; comment?: string };
export class Code {
lines: CodeLine[];
constructor(code: string, commentDelim: string);
constructor(code: string[], commentDelim: string);
constructor(code: string | string[], commentDelim: string) {
if (typeof code === 'string') {
this.lines = this.trimComments(lines(code.trimRight() + '\n'), commentDelim);
} else {
this.lines = this.trimComments(code, commentDelim);
}
}
/**
* Removes trailing comments, along with any preceding whitespace.
* Returns an array of objects (one for each line) to be passed to extractCode.
*/
trimComments(inLines: string[], delim: string): CodeLine[] {
const lines: CodeLine[] = [];
const regex = new RegExp('(\\s*' + delim + ')', 'g');
inLines.forEach((line) => {
const segs = line.split(regex);
const ln: CodeLine = { code: segs[0] };
if (segs.length > 1) {
ln.comment = segs.reduce((c, seg, i) => (i > 1 ? c + seg : seg), '');
}
lines.push(ln);
});
return lines;
}
/**
* All newlines are \n
*/
extractCode(withComments = false): string {
return this.lines.reduce((acc, line, i, lines) => {
return (
acc +
line.code +
(line.comment && withComments ? line.comment : '') +
(i < lines.length - 1 ? '\n' : '')
);
}, '');
}
}