-
Notifications
You must be signed in to change notification settings - Fork 0
/
preprocess.js
91 lines (84 loc) · 1.71 KB
/
preprocess.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
'use strict';
const { createInterface } = require('readline');
const rl = createInterface({ input: process.stdin });
const toc = [];
let tocLevel = 0;
let hasToC = false;
const buffer = [];
let inToC = false;
const output = !process.argv.includes('--toc');
const handler = (line, addToC = false) => {
const match = line.match(/^(?<level>#+) (?<title>.+)/);
if (match) {
const { groups: { level, title } } = match;
if (addToC) {
toc.push([ level.length - 1, title ]);
}
if (title === 'TOC' || title === 'Table of Contents') {
tocLevel = level.length;
if (hasToC) {
buffer.push(line);
}
hasToC = true;
return;
}
}
if (hasToC) {
buffer.push(line);
return;
}
if (line === '[//]: # (TOC:START)') {
inToC = true;
}
if (line === '[//]: # (TOC:END)') {
inToC = false;
return;
}
if (!inToC && output) {
console.log(line);
}
};
const done = () => {
if (hasToC) {
if (output) {
console.log('#'.repeat(tocLevel) + ' Table of Contents\n');
console.log('[//]: # (TOC:START)\n');
}
toc.forEach(([ level, title ]) =>
console.log(
'\t'.repeat(level) +
'1. [' +
title +
'](#' +
title
.toLowerCase()
.replace(/[^- \w]/g, '')
.replace(/ /g, '-') +
')'));
if (output) {
console.log('');
console.log('[//]: # (TOC:END)\n');
}
hasToC = false;
while (buffer[0] === '') {
buffer.splice(0, 1);
}
buffer
.reduce((acc, x) => [
...acc,
// eslint-disable-next-line no-nested-ternary
...acc[acc.length - 1] === ''
? x === ''
? []
: [ x ]
: [ x ]
], [])
.splice(0, Infinity)
.forEach(handler);
if (hasToC) {
done();
}
}
};
rl.on('line', line => handler(line, true));
rl.once('close', done);