This repository has been archived by the owner on Apr 15, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sections.js
90 lines (71 loc) · 2.02 KB
/
sections.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
/*
I have not used CoffeeScript in a while, so I had to first write messy working solution
in JavaScript and than I rewrote it as CoffeeScript.
*/
var md = require('markdown').markdown;
module.exports = function sections(markdown) {
var tree = md.parse(markdown);
if (tree.length === 1) {
return {
sections: []
}
}
var mainHeadingLevel = null,
subsectionHeadingLevel = null,
currentSection = null,
mainSection = null,
subsection = null,
contentStart = 1,
currentPosition = 1,
mainSections = [];
function closeCurrentSection() {
if (currentPosition !== 1) {
if (currentSection === null) { // preamble
currentSection = {name: null};
mainSections.push(currentSection);
}
// single node, place directly
if (contentStart === currentPosition - 1) {
currentSection.text = tree[contentStart];
} else if (contentStart !== currentPosition) {
currentSection.text = tree.slice(contentStart, currentPosition);
}
}
contentStart = currentPosition + 1
}
for (; currentPosition < tree.length; currentPosition++) {
var node = tree[currentPosition],
level,
headingContent;
if (node[0] !== 'header') {
continue; // no processing
}
if (currentPosition !== 1) {
}
if (node.length === 3 && !Array.isArray(node[2])) { // simple text as content
headingContent = node[2];
} else { // content is array
headingContent = node.slice(2);
}
level = node[1].level;
if (mainHeadingLevel === null || level <= mainHeadingLevel) {
closeCurrentSection();
mainHeadingLevel = level;
subheadingLevel = null;
mainSection = currentSection = {name: headingContent};
mainSections.push(currentSection);
} else if (subheadingLevel === null || level <= subheadingLevel) {
closeCurrentSection();
subheadingLevel = level;
currentSection = {name: headingContent};
if (!('subsections' in mainSection)) {
mainSection.subsections = [];
}
mainSection.subsections.push(currentSection);
}
}
closeCurrentSection();
return {
sections: mainSections,
};
}