-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtoc.js
61 lines (54 loc) · 1.49 KB
/
toc.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
/**
* Helper for generating table of contents in Markdown files
*/
const fs = require("fs");
// this is basically a MD comment to mark that the TOC exists
const endStringMarker = "__endtoc__";
const endString = `[//]: # "${endStringMarker}"`;
// removes any existing TOC if it exists
function removeTOC(input) {
let next = input;
const index = next.indexOf(endString);
if (index >= 0) {
next = input.slice(index + endString.length);
}
return next.trim();
}
// converts arbitrary strings into Markdown links
function stringToLink(str) {
const anchor = str
.trim()
.toLowerCase()
// only keep alphanumeric, spaces, and dashes
.replaceAll(/[^a-z0-9 -]/g, "")
// replace spaces with dashes
.replaceAll(/\s+/g, "-");
const text = str.trim();
return `[${text}](#${anchor})`;
}
// generate a new TOC
function generateTOC(input) {
let toc = "";
input.split("\n").forEach((line) => {
// ignore H1, only handle H2+
const match = line.match(/^(#{2,})(.+)/);
if (match) {
const a = stringToLink(match[2]);
const indent = " ".repeat(match[1].length - 2);
toc += `${indent}- ${a}\n`;
}
});
return `${toc}\n${endString}\n\n`;
}
function main() {
const file = process.argv[2];
if (!file) {
throw new Error("file required: node toc.js [PATH]");
}
const data = fs.readFileSync(file, "utf-8");
const doc = removeTOC(data);
const toc = generateTOC(doc);
const combined = `${toc}${doc}`;
fs.writeFileSync(file, combined);
}
main();